Map: forEach example: Java 8 !!!






Below example will show the demonstration of how to use forEach; new Java 8 feature with List and Map.

        Looping Map with forEach

General way to loop a Map:

 -----------Test.java------------

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Test {
       public static void main(String[] args) {
              Map<Integer, String> items = new HashMap<>();
              items.put(1, "One");
              items.put(2, "Two");
              items.put(3, "Three");
              items.put(4, "four");
              items.put(5, "five");

              for (Entry<Integer, String> entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
              }
       }
}



Output:
-------------------------

Item : 1 Count : One
Item : 2 Count : Two
Item : 3 Count : Three
Item : 4 Count : four
Item : 5 Count : five


 ----------------------------------------




Looping Map with forEach, 

 

Actually in Java 8, we can loop by using lambda expression

 

 Code:

------------------------------------------------------------
import java.util.HashMap;
import java.util.Map;

public class Test {
       public static void main(String[] args) {
              Map<Integer, String> items = new HashMap<>();

              items.put(1, "One");
              items.put(2, "Two");
              items.put(3, "Three");
              items.put(4, "four");
              items.put(5, "five");

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

             
       }
}



Output:

---------------------------------------------------------
Item : 1 Count : One
Item : 2 Count : Two
Item : 3 Count : Three
Item : 4 Count : four
Item : 5 Count : five





No comments:

Post a Comment

Fixing yum command on linux

You may find yourself having to fix more packages. So you can just remove everything you had installed via  pip and reinstall everythin...