The
LinkedHashSet
is similar to theHashSet
, except that theLinkedHashSet
maintains the insertion order of elements, whereasHashSet
does not. Read more aboutLinkedHashSet
here.
The removeIf
method will remove all the elements of the LinkedHashSet
object, which satisfies the given predicate.
default boolean removeIf(Predicate<? super E> filter)
This method takes the
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 isnull
.
This method returns true
if any elements have been removed.
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
.