Click here to watch in Youtube :
https://www.youtube.com/watch?v=sAELCo4DxsI&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java Tutorial: Lambda expression in java | Java Lambda expressions[forEach method of Map] |
import java.util.LinkedHashMap; import java.util.Map; public class LambdaDemo1 { public static void main(String[] args) { Map<Integer, String> map = new LinkedHashMap<>(); map.put(1, "Peter"); map.put(2, "John"); map.put(3, "Juli"); map.put(4, "Stephan"); /* * Normal way to loop a Map.Before Java 8 */ for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue()); } System.out.println("------------------------------------"); /* * In Java 8, we can loop a Map with forEach + lambda expression. */ map.forEach((k, v) -> System.out.println("key : " + k + " value : " + v)); } }Output
key : 1, value : Peter key : 2, value : John key : 3, value : Juli key : 4, value : Stephan ------------------------------------ key : 1 value : Peter key : 2 value : John key : 3 value : Juli key : 4 value : StephanLambdaDemo2.java
import java.util.LinkedHashMap; import java.util.Map; public class LambdaDemo2 { public static void main(String[] args) { Map<Integer, String> map = new LinkedHashMap<>(); map.put(1, "Peter"); map.put(2, "John"); map.put(3, "Juli"); map.put(4, "Stephan"); /* * In Java 8, we can loop a Map with forEach + lambda * expression+multiple statements. */ map.forEach((k, v) -> { System.out.println("key : " + k + " value : " + v); if ("John".equals(v)) { System.out.println("Hello John"); } }); } }Output
key : 1 value : Peter key : 2 value : John Hello John key : 3 value : Juli key : 4 value : StephanRefer:
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Map.html
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/LambdaDemo_map_foreach_app.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/LambdaDemo_map_foreach_app
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/4c13bd19ff03c6acdc5e87d7803290d625ce640a/BasicJava/LambdaDemo_map_foreach_app/?at=master
See also:
No comments:
Post a Comment