What is the LinkedHashSet.removeIf in Java?

The LinkedHashSet is similar to the HashSet, except that the 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, which satisfies the given predicate.

Syntax

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

This method takes the Predicate functionThese are functions that return “TRUE” or “FALSE”. Predicate functions are used to check if the input satisfies particular conditions. as an argument.

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

The NullPointerException is thrown if the argument is null.

This method returns true if any elements have been 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’ve created a new LinkedHashSet object and added the three elements, 1,2,3, to it. We then 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 the even numbers from the set. In our case, the elements in the set are 1,2,3. 2 is the only even number in this set, so it will be removed from the set.

Free Resources