在迭代过程中更改HashMap键

24

在迭代过程中更改同一HashMap实例的键是否可能?因为Map条目集没有entry.setKey()方法。现在我能想到的是创建另一个HashMap...

MultipartParsingResult parsingResult = parseRequest(request);

Map<String, String[]> mpParams = parsingResult.getMultipartParameters();
Map<String, String[]> mpParams2 = new HashMap<String, String[]>();

Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator();

while (it.hasNext()) {
    Entry<String,String[]> entry = it.next();
    String name = entry.getKey();

    if (name.startsWith(portletNamespace)) {
        mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue());
    }
    else {
        mpParams2.put(name, entry.getValue());
    }
}
5个回答

21

也许这可以帮助你:

map.put(newkey,map.remove(oldkey));

2
如果我正在迭代键集,那么这个新添加的键会出现在现有的键集中吗? - Ring

10

在迭代过程中,您应该将信息保存在其他集合中以便修改。您只能在迭代器期间使用iterator.remove()来删除条目。HashMap合同禁止在迭代期间对其进行变异。


6
你永远无法在 Map 中更改键的值。 - user207421
从性能角度来看,我这里的解决方案还可以吗?因为每小时会有成千上万次这样的调用。 - lisak
@EJP,我在这里更改的只是一个映射表的键。 - lisak
1
这就是我的观点。你不能更改Map中键对象的值。请参阅Map的Javadoc。 - user207421

3
HashMap 中有四种常见的修改方式,你可能想要对键或值进行修改。
  1. 要更改 HashMap 键,可以使用 get 查找值对象,然后使用新键删除旧键并将其插入。
  2. 要更改值对象中的字段,请使用 get 按键查找该值对象,然后使用其 setter 方法。
  3. 要完全替换值对象,只需在旧键处放置一个新值对象即可。
  4. 要用基于旧对象的新对象替换值对象,请使用 get 查找值对象,创建一个新对象,从旧对象中复制数据,然后在相同键下放置新对象。
类似以下示例。
static class Food
    {
    // ------------------------------ FIELDS ------------------------------

    String colour;

    String name;

    float caloriesPerGram;
    // -------------------------- PUBLIC INSTANCE  METHODS --------------------------

    public float getCaloriesPerGram()
        {
        return caloriesPerGram;
        }

    public void setCaloriesPerGram( final float caloriesPerGram )
        {
        this.caloriesPerGram = caloriesPerGram;
        }

    public String getColour()
        {
        return colour;
        }

    public void setColour( final String colour )
        {
        this.colour = colour;
        }

    public String getName()
        {
        return name;
        }

    public void setName( final String name )
        {
        this.name = name;
        }

    public String toString()
        {
        return name + " : " + colour + " : " + caloriesPerGram;
        }

    // --------------------------- CONSTRUCTORS ---------------------------

    Food( final String name, final String colour, final float caloriesPerGram )
        {
        this.name = name;
        this.colour = colour;
        this.caloriesPerGram = caloriesPerGram;
        }
    }

// --------------------------- main() method ---------------------------

/**
 * Sample code to TEST HashMap Modifying
 *
 * @param args not used
 */
public static void main( String[] args )
    {
    // create a new HashMap
    HashMap<String, Food> h = new HashMap<String, Food>( 149
            /* capacity */,
            0.75f
            /* loadfactor */ );

    // add some Food objecs to the HashMap
    // see http://www.calorie-charts.net  for calories/gram
    h.put( "sugar", new Food( "sugar", "white", 4.5f ) );
    h.put( "alchol", new Food( "alcohol", "clear", 7.0f ) );
    h.put( "cheddar", new Food( "cheddar", "orange", 4.03f ) );
    h.put( "peas", new Food( "peas", "green", .81f ) );
    h.put( "salmon", new Food( "salmon", "pink", 2.16f ) );

    // (1) modify the alcohol key to fix the spelling error in the key.
    Food alc = h.get( "alchol" );
    h.put( "alcohol", alc );
    h.remove( "alchol" );

    // (2) modify the value object for sugar key.
    Food sug = h.get( "sugar" );
    sug.setColour( "brown" );
    // do not need to put.

    // (3) replace the value object for the cheddar key
    // don't need to get the old value first.
    h.put( "cheddar", new Food( "cheddar", "white", 4.02f ) );

    // (4) replace the value object for the peas key with object based on previous
    Food peas = h.get( "peas" );
    h.put( "peas", new Food( peas.getName(), peas.getColour(), peas.getCaloriesPerGram() * 1.05f ) );

    // enumerate all the keys in the HashMap in random order
    for ( String key : h.keySet() )
        {
        out.println( key + " = " + h.get( key ).toString() );
        }
    }// end main
}

我希望您能从中受益。

1
当我需要更改地图条目的键时,我进入了这个线程。在我的情况下,我有一个Map中的JSON表示,意味着它可以容纳Map或Map列表,以下是代码:
private Map<String,Object> changeKeyMap(Map<String, Object> jsonAsMap) throws InterruptedException {

    Map<String,Object> mapClone = new LinkedHashMap<>();
    for (Map.Entry<String, Object> entry : jsonAsMap.entrySet()) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
        Object value = entry.getValue();
        if (entry.getValue() instanceof Map) {
            value = changeKeyMap((Map) entry.getValue());
        } else if (isListOfMaps(entry.getValue())) {
            value = changeKeyListOfMaps((List<Map<String, Object>>) entry.getValue());
        }
        String changedKey = changeSingleKey(entry.getKey());
        mapClone.put(changedKey, value);
    }
    return mapClone;
}

private List<Map<String,Object>> changeKeyListOfMaps(List<Map<String,Object>> listOfMaps) throws InterruptedException {
    List<Map<String,Object>> newInnerMapList = new ArrayList<>();
    for(Object singleMapFromArray :listOfMaps){
        Map<String,Object> changeKeyedMap = changeKeyMap((Map<String, Object>) singleMapFromArray);
        newInnerMapList.add(changeKeyedMap);
    }
    return newInnerMapList;
}
private boolean isListOfMaps(Object object) {
    return object instanceof List && !((List) object).isEmpty() && ((List) object).get(0) instanceof Map;
}

private String changeSingleKey(String originalKey) {
    return originalKey + "SomeChange"
}

在我的语言中有一句谚语:“我买了糖浆,但事实上它是蜂蜜。”我觉得这对你的回答非常相关。谢谢Robocide! - gdrt

0

最好的做法是将地图复制到一个新的地图中,并进行所需的修改,然后返回这个新地图并销毁旧的地图。 不过,我想知道这种解决方案的性能影响。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接