Skip to main content

Java 8 forEach examples

java 8 foreach examples

In this article, I am going to show you how to loop a List and a Map by using new Java 8 forEach statement.

1- forEach and List

1.1 Normal for-loop to loop a List.

List<String> names = new ArrayList<>();
names.add("A");
names.add("B");
names.add("C");
names.add("D");
names.add("E");

// Output : A,B,C,D,E
for (String name : names) {
	System.out.println(name);
}

1.2 In Java 8, we can loop a List by using forEach + lambda expression or method reference.

List<String> names = new ArrayList<>();
names.add("A");
names.add("B");
names.add("C");
names.add("D");
names.add("E");

// Lambda Expression
// Output : A,B,C,D,E
names.forEach(name -> System.out.println(name));

// Method Reference
// Output : A,B,C,D,E
names.forEach(System.out::println);

// Output : D
names.forEach(name -> {
	if ("D".equals(name)) {
		System.out.println(name);
	}
});

//Stream and Filter
// Output : D
names.stream().filter(p -> p.contains("D"))
		.forEach(System.out::println);

2. forEach and Map

2.1 Normal way to loop a Map.

Map<String, Integer> details = new HashMap<>();
details.put("A", 100);
details.put("B", 200);
details.put("C", 300);
details.put("D", 400);
details.put("E", 500);
details.put("F", 600);

for (Map.Entry<String, Integer> detail : details.entrySet()) {
	System.out.println("Name : " + detail.getKey()
			+ " Roll No : " + detail.getValue());
}

2.2 In Java 8, we can loop a Map by using forEach + lambda expression.

Map<String, Integer> details = new HashMap<>();
details.put("A", 100);
details.put("B", 200);
details.put("C", 300);
details.put("D", 400);
details.put("E", 500);
details.put("F", 600);

details.forEach((k, v) -> System.out.println(
				"Name : " + k + " Roll No : " + v));

details.forEach((k, v) -> {
	System.out.println(
			"Name : " + k + " Roll No : " + v);
	if ("D".equals(k)) {
		System.out.println("Welcome D");
	}
});

Feel free to write comments and suggestion. I always eager to help you.

Leave a Reply

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

Top