This example demonstrates the usage of forEach function with lambda expressions in Java.
Check out more examples at https://www.javaguides.net/2018/06/guide-to-java-8-foreach-method.html.
Loop a List with forEach + lambda expression
In Java 8, you can loop a List with forEach + lambda expression or method reference.
public static void forEachWithList() {
final List < Person > items = new ArrayList < > ();
items.add(new Person(100, "Ramesh"));
items.add(new Person(100, "A"));
items.add(new Person(100, "B"));
items.add(new Person(100, "C"));
items.add(new Person(100, "D"));
//lambda
items.forEach(item - > System.out.println(item.getName()));
//Output : C
items.forEach(item - > {
if ("C".equals(item)) {
System.out.println(item);
}
});
//method reference
//Output : A,B,C,D,E
items.forEach(System.out::println);
//Stream and filter
//Output : B
items.stream()
.filter(s - > s.getName().equals("Ramesh"))
.forEach(System.out::println);
}
Please refer to the comments in the above example are self-descriptive.
Loop a Map with forEach and lambda expressions
In Java 8, you can loop a Map with forEach and lambda expressions.
public static void forEachWithMap() {
// Before Java 8, how to loop map
final Map < Integer, Person > map = new HashMap < > ();
map.put(1, new Person(100, "Ramesh"));
map.put(2, new Person(100, "Ram"));
map.put(3, new Person(100, "Prakash"));
map.put(4, new Person(100, "Amir"));
map.put(5, new Person(100, "Sharuk"));
// In Java 8, you can loop a Map with forEach + lambda expression.
map.forEach((k, p) - > {
System.out.println(k);
System.out.println(p.getName());
});
}
Comments
Post a Comment