What is the LinkedHashSet.forEach in Java?

The LinkedHashSet is similar to the HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not. We can read more about LinkedHashSet here.

The forEach method performs an action on each element of the LinkedHashSet object.

Syntax

default void forEach(Consumer<? super T> action)

Parameter(s)

  • Consumer<? super T> action: It is the consumer functionIt represents an operation that accepts a single input argument, and returns no result. that is executed for each element of the set.

  • This method doesn’t return any value.

Code

import java.util.LinkedHashSet;
class forEach {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.forEach((e)->{
System.out.println(e*2);
});
}
}

In the code above,

  • In line number 1: We import the LinkedHashSet class.

  • In line number 4: We create a LinkedHashSet object with the name set which can only contain Integer objects as elements.

  • From line number 5 to 7: Add three elements (1,2,3) to it using the add method.

  • In line number 8: We use the forEach method with the lambda function as an argument. The passed function will multiply the current value by 2, and print it. The forEach method will loop through each element of the set in their insertion order and execute the passed function.

Free Resources