Java 8 – forEach loop statement examples

The for-each construct gets rid of the clutter and the opportunity for error.

Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection e.g. List, Set, or Map by converting them into a java.util.sttream.Stream instance.

Below are the examples to show how to loop a List and a Map with the new Java 8 forEach statement.

forEach statement to traverse List:

List<String> exampleList = new ArrayList<>();
exampleList.add("Java");
exampleList.add("JavaSE");
exampleList.add("Java8");
exampleList.add("JavaME");

for(String item : exampleList){
	System.out.println(item);
}
//lambda
//Output : Java,JavaSE,Java8,JavaME
exampleList.forEach(item->System.out.println(item));

//Output : Java8
exampleList.forEach(item->{
	if("Java8".equals(item)){
		System.out.println(item);
	}
});

//method reference
//Output : Java,JavaSE,Java8,JavaME
exampleList.forEach(System.out::println);

//Stream and filter
//Output : Java
exampleList.stream()
	.filter(s->s.contains("Java"))
	.forEach(System.out::println);

forEach statement to traverse Map:

Map<String, Integer> exampleMap = new HashMap<>();
exampleMap.put("Dogs", 2);
exampleMap.put("Cats", 3);
exampleMap.put("Horses", 4);
exampleMap.put("Buffaloes", 2);


for (Map.Entry<String, Integer> entry : exampleMap.entrySet()) {
	System.out.println("Animal : " + entry.getKey() + " Count : " + entry.getValue());
}
exampleMap.forEach((key,value)->System.out.println("Animal : " + key + " Count : " + value));

exampleMap.forEach((key,value)->{
	System.out.println("Animal : " + key + " Count : " + value);
	if("Cats".equals(key)){
		System.out.println("Hello Cat");
	}
});

References:

  1. Java 8 Iterable forEach JavaDoc
  2. Java 8 forEach JavaDoc

Posted

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *