Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashset
java
communitycreator

What is the LinkedHashSet.removeIf 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. Read more about LinkedHashSet here.

The removeIf method will remove all the elements of the LinkedHashSet object that satisfy the given predicate.

Syntax

default boolean removeIf(Predicate<? super E> filter)

This method takes the Predicate functionfunctions that return TRUE or FALSE. You use predicate functions to check if input satisfies some condition as an argument.

The removeIf method will loop each element in the insertion order and apply the predicate function. During the iteration, the element will be removed from the set if the predicate returns true.

The NullPointerException is thrown if the argument is null.

This method returns true if any elements were removed.

Code

import java.util.LinkedHashSet;
class RemoveIf {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.removeIf((e)->{
return e%2 == 0;
});
System.out.println("The set is "+ set);
}
}

In the above code, we have created a new LinkedHashSet object and added three elements (1,2,3) to it. Then, we called the removeIf method with a predicate function. This function will return true if the element is an even number. The result of removeIf will be the removal of all even numbers from the set. In our case, the elements in the set are 1,2,3. So, since 2 is the only even number it is the only one that will be removed from the set.

RELATED TAGS

linkedhashset
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