Java 8 provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface.
It is a default method defined in the Iterable interface. Collection classes that extend the Iterable interface can use the forEach() loop to iterate elements.
It is a default method defined in the Iterable interface. Collection classes that extend the Iterable interface can use the forEach() loop to iterate elements.
Java 8 forEach() method with Set Example
The below example shows how to use the forEach method with Set collection, stream, etc.
public static void forEachWithSet() {
final Set < String > items = new HashSet < > ();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
// before java 8
for (final String item: items) {
System.out.println(item);
}
// java 8 with lambda expression
//Output : A,B,C,D,E
items.forEach(item - > System.out.println(item));
//Output : C
items.forEach(item - > {
if ("C".equals(item)) {
System.out.println(item);
}
});
//method reference
items.forEach(System.out::println);
//Stream and filter
items.stream()
.filter(s - > s.contains("B"))
.forEach(System.out::println);
}
Reference
Related Java HashSet Source Code Examples
- Creating a HashSet and Adding New Elements to It
- Java 8 forEach() Set Example
- Java Convert Array to Set
- Iterating over a HashSet using Iterator
- Iterate over HashSet in Java
- Remove Element from HashSet in Java
- Create HashSet in Java