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 forEach loop, in Java 8, provides programmers a new, interesting and concise way of iterating over a Collection. Lambda expression is also a new and important feature of Java which was included in Java 8. It provides a concise and clear way to represent one method interface using an expression. It is also very useful in the collection library.

 

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.

About Author

Author Image
Shakil Pathan

Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .

Request for Proposal

Name is required

Comment is required

Sending message..