Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the LinkedHashSet.forEach in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
});
}
}
The code above uses `forEach`method to multiply and print the set elements by 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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring