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));
}
}
Outputkey : 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 : Stephan
LambdaDemo2.javaimport 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");
}
});
}
}
Outputkey : 1 value : Peter
key : 2 value : John
Hello John
key : 3 value : Juli
key : 4 value : Stephan
Refer: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
No comments:
Post a Comment