Java 8 forEach and Lambda Expression For Map and List
Posted By : Shakil Pathan | 30-Apr-2018
Hi Guys,
In this blog, I am going to explain you about how to loop over a List and a Map with the new Java 8 features forEach and lambda expression.
The
The below code is a normal way to loop over a Map:
Map<String, Integer> vehicles = new HashMap<>();
vehicles.put("car", 40);
vehicles.put("bus", 20);
vehicles.put("train", 10);
vehicles.put("bike", 30);
for (Map.Entry<String, Integer> entry : vehicles.entrySet()) {
System.out.println("vehicles : " + entry.getKey() + " Count : " + entry.getValue());
}
In Java 8, you can loop over a Map with forEach and lambda expression like:
vehicles.forEach((k,v)->System.out.println("vehicles : " + k + " Count : " + v));
vehicles.forEach((k,v)->{
System.out.println("vehicles : " + k + " Count : " + v);
if("bike".equals(k)){
System.out.println("Hello bike");
}
});
Below is an example of List:
List<String> vehicles = new ArrayList<>();
vehicles.add("car");
vehicles.add("bus");
vehicles.add("train");
vehicles.add("bike");
for(String vehicle : vehicles){
System.out.println(vehicle);
}
In Java 8, you can loop over a List with forEach and lambda expression like:
vehicles.forEach(vehicle->System.out.println(vehicle));
vehicles.forEach(vehicle->{
if("bike".equals(vehicle)){
System.out.println(vehicle);
}
});
vehicles.forEach(System.out::println);
vehicles.stream()
.filter(s->s.contains("bike"))
.forEach(System.out::println);
Hope, It helps you to understanding the concepts!
Thanks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .