Java ArrayList Examples
- Java ArrayBlockingQueue Example
- Java Convert Array to Set
- Copying part of Array in Java Example
- Sorting an Array using Arrays.sort() Method
- Check Two Arrays are Deeply Equal
- Java Arrays.copyOf() Example - Copying an Array
- Java Arrays.binarySearch() Example - Searching an Array
- Java Arrays.asList() Example - Convert Array to ArrayList
- Java Convert Array to Stack Example
- What's the Simplest Way to Print a Java Array?
- Java Pyramid Examples
- How to Check if Two Arrays are Equal in Java
- Create and Initialize Two Dimensional Array in Java
- How to Initialize an Array in Java in One Line
- Java Array - Create, Declare, Initialize and Print Examples
- Java Array Simple Program
Array Methods with Examples
- Java ArrayList add() Method
- Java ArrayList addAll() Method
- Java ArrayList clear() Method
- Java ArrayList contains() Method
- Java ArrayList ensureCapacity() Method
- Java ArrayList clone() Method
- Java ArrayList get() Method
- Java ArrayList indexOf() Method
- Java ArrayList remove() Method
- Java ArrayList removeAll() Method
- Java ArrayList removeIf() Method
- Java ArrayList retainAll() Method
- Java ArrayList sort() Method
- Java ArrayList spliterator() Method
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.
Normal for loop with List
Let's use normal for-loop to loop a List.
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"));
for (final Person item: items) {
System.out.println(item.getName());
}
}
forEach() method with List Example
In Java 8, you can loop a List with forEach + lambda expression or method reference. Please refer to the comments in the above example are self-descriptive.
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);
}
Comments
Post a comment