java 一次更新HashMap中的所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16588492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:23:31  来源:igfitidea点击:

Update all values at a time in HashMap

javahashmap

提问by NPKR

I have a HashMapwith some Keys - Values.

我有HashMap一些Keys - Values

On some condition I want to update allvalues to single value regardless of keys.

在某些情况下,无论键如何,我都想将所有值更新为单个值。

Is there any util or predefined methods to do this, without for loop?

在没有 for 循环的情况下,是否有任何实用程序或预定义的方法可以做到这一点?

Any suggestions?

有什么建议?

回答by Kevin Meredith

if (yourCondition) { 
      for (Map.Entry<String, String> entry : map.entrySet()) {
          map.put(entry.getKey(), MY_VALUE);
      }
}

Or for java 8 or higher (without a loop)

或者对于 java 8 或更高版本(没有循环)

if (yourCondition) { 
      map.replaceAll( (k,v)->v=MY_VALUE );
}

回答by Maroun

You can use iterator on entrySet:

您可以在entrySet上使用迭代器:

Iterator it = yourMap.entrySet().iterator();
Map.Entry keyValue;
while (it.hasNext()) {
    keyValue = (Map.Entry)it.next();
    //Now you can have the keys and values and easily replace the values...
}

Note that the internal implementation of the iterator still uses a for loop :)

请注意,迭代器的内部实现仍然使用 for 循环 :)

回答by Igor Konoplyanko

Try to use Guava:

尝试使用番石榴

Collections2.transform(stringStringHashMap.values(), new Function<String, String>() {
  @Override
  public String apply(java.lang.String s) {
    return "modified string";
  }
});

回答by Igor Konoplyanko

It's not clear how you plan to set it to a single value, but you can call putAllon the HashMapas demonstrated from this answer:

目前尚不清楚你打算怎样将它设置为一个值,但你可以叫putAllHashMap从这个证明答案

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

patchis the mapyou are adding to target.

patchmap您要添加到target.

patchcould be a HashMapcontaining the same value for all keys....

patch可能是HashMap所有键都包含相同的值....

回答by heikkim

Extend the HashMap and make your implementation return your magic value if some condition is set.

如果设置了某些条件,则扩展 HashMap 并使您的实现返回您的魔法值。