用于映射条目集的 forEach 循环 Java 8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32264773/
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-08-11 12:14:20  来源:igfitidea点击:

forEach loop Java 8 for Map entry set

javalambdajava-8

提问by Siddharth Sachdeva

I'm trying to convert old conventional for each loop till java7 to java8's for each loop for a map entry set but I'm getting an error. Here's the code I'm trying to convert:

我正在尝试将每个循环的旧常规转换为 java7 到 java8 的每个循环的映射条目集,但我收到错误。这是我要转换的代码:

for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }

Here's the changes I have done:

这是我所做的更改:

map.forEach( Map.Entry<String, String> entry -> {
       System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());

   }); 

I tried doing this as well :

我也尝试这样做:

Map.Entry<String, String> entry;
   map.forEach(entry -> {
       System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());

   });

But still facing error. The error I'm getting for this is : Lambda expression's signature does not match the signature of the functional interface method accept(String, String)

但仍然面临错误。我为此得到的错误是:Lambda 表达式的签名与功能接口方法的签名不匹配accept(String, String)

采纳答案by JB Nizet

Read the javadoc: Map<K, V>.forEach()expects a BiConsumer<? super K,? super V>as argument, and the signature of the BiConsumer<T, U>abstract method is accept(T t, U u).

阅读javadocMap<K, V>.forEach()期望一个BiConsumer<? super K,? super V>作为参数,BiConsumer<T, U>抽象方法的签名是accept(T t, U u)

So you should pass it a lambda expression that takes two inputs as argument: the key and the value:

所以你应该向它传递一个 lambda 表达式,它接受两个输入作为参数:键和值:

map.forEach((key, value) -> {
    System.out.println("Key : " + key + " Value : " + value);
});

Your code would work if you called forEach() on the entry set of the map, not on the map itself:

如果您在地图的条目集而不是地图本身上调用 forEach() ,您的代码将起作用:

map.entrySet().forEach(entry -> {
    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}); 

回答by Evgeny Tugarev

Maybe the best way to answer the questions like "which version is faster and which one shall I use?" is to look to the source code:

也许是回答诸如“哪个版本更快,我应该使用哪个版本?”之类的问题的最佳方法。是查看源代码:

map.forEach()- from Map.java

map.forEach()- 来自 Map.java

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

javadoc

文档

map.entrySet().forEach()- from Iterable.java

map.entrySet().forEach()- 来自 Iterable.java

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

javadoc

文档

This immediately reveals that map.forEach()is also using Map.Entryinternally. So I would not expect any performance benefit in using map.forEach()over the map.entrySet().forEach(). So in your case the answer really depends on your personal taste :)

这立即表明map.forEach()也在内部使用Map.Entry。所以我不希望使用map.forEach()map.entrySet().forEach() 有任何性能优势。所以在你的情况下,答案真的取决于你的个人品味:)

For the complete list of differences please refer to the provided javadoc links. Happy coding!

有关差异的完整列表,请参阅提供的 javadoc 链接。快乐编码!

回答by Shridhar Sangamkar

You can use the following code for your requirement

您可以根据您的要求使用以下代码

map.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

回答by vaibhav1111

HashMap<String,Integer> hm = new HashMap();

 hm.put("A",1);
 hm.put("B",2);
 hm.put("C",3);
 hm.put("D",4);

 hm.forEach((key,value)->{
     System.out.println("Key: "+key + " value: "+value);
 });

回答by vivek

Stream API

流API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}