99

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:

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)

8 Answers 8

217

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).

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

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:

map.entrySet().forEach(entry -> {
    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}); 
5
  • Great. Now working both. But which one is a better way? In which case performance would be better? @JBNizet Aug 28, 2015 at 7:47
  • 2
    The second version forces a Map.Entry instance to be created for each entry; the first one gives you key and value with no instantiation. Therefore Map.Entry is a middleman and you can avoid that using the first version. Aug 28, 2015 at 7:47
  • 6
    @Marko Topolnik: for most Map implementations, the Map.Entry instances already exist prior to the iteration and don’t need to be created. Still, not having to deal with Map.Entry in the action is a win on readability and has a slight potential for better performance as no additional method invocations are required to retrieve the key and value.
    – Holger
    Aug 28, 2015 at 8:01
  • 2
    @Holger I'll stress your tacit implication: for most, but not all, Map implementations that is true, ConcurrentHashMap being an important counterexample. Aug 28, 2015 at 8:04
  • 1
    @Marko Topolnik: but when iterating over an entire ConcurrentHashMap, temporary entry instances are the last thing to worry about. Nevertheless, we agree on preferring map.forEach((key, value) -> …); anyway…
    – Holger
    Aug 28, 2015 at 8:08
16

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

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

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.Entry internally. 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 :)

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

6

You can use the following code for your requirement

map.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
1
  • 4
    This answer is identical to part of the answer provided by JB Nizet 2 years earlier and provides no additional, useful information.
    – Madbreaks
    Sep 21, 2018 at 19:10
2
String ss = "Pawan kavita kiyansh Patidar Patidar";
    StringBuilder ress = new StringBuilder();
    
    Map<Character, Integer> fre = ss.chars().boxed()
            .collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
    
      //fre.forEach((k, v) -> System.out.println((k + ":" + v)));
    
    fre.entrySet().forEach(e ->{
            //System.out.println(e.getKey() + ":" + e.getValue());
            //ress.append(String.valueOf(e.getKey())+e.getValue());
        }); 

    fre.forEach((k,v)->{
        //System.out.println("Item : " + k + " Count : " + v);
        ress.append(String.valueOf(k)+String.valueOf(v));
    });
    
    System.out.println(ress.toString());
1
  • While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Sep 12, 2020 at 20:54
2

Below are the tree best ways to do it 1.Iterate with entry set

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}
  1. Lambdas map.forEach((k, v) -> System.out.println((k + ":" + v)));

3 stream map.entrySet().stream() .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));

1
Map<Integer,String> result=new  HashMap<Integer, String>();

result.put(1, "Motorbike");
result.put(2, "Car");
result.put(3, "Jeep");

result.forEach((key,value)->System.out.println(key+ "  "+value));
0
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);
 });
1
  • Please add some explanation to your answer. This will help others adapt your answer to their own needs. From Review.
    – Wai Ha Lee
    Mar 3, 2019 at 13:45
0

Stream API

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.