removeIf(Predicate): This method is available in java.util.LinkedHashSet class of Java.
Syntax:
boolean java.util.Collection.removeIf(Predicate<? super K> filter)
This method takes one argument. This method removes all of the elements of this collection that satisfy the given predicate.
Parameters: One parameter is required for this method.
filter: a predicate which returns true for elements to be removed.
Returns: true if any elements were removed.
Throws:
1. NullPointerException - if the specified filter is null.
2. UnsupportedOperationException - if elements cannot be removed from this collection.
Approach 1: When no exception
Java
import java.util.LinkedHashSet;import java.util.function.Predicate;public class LinkedHashSetremoveIf {public static void main(String[] args) {LinkedHashSet<Integer> linkedHashSet =new LinkedHashSet<>();linkedHashSet.add(10);linkedHashSet.add(20);linkedHashSet.add(15);Predicate<Integer> filter = (i) -> i > 10;linkedHashSet.removeIf(filter);System.out.println(linkedHashSet);}}
Output:
[10]
Approach 2: NullPointerException
Java
import java.util.LinkedHashSet;import java.util.function.Predicate;public class LinkedHashSetremoveIf {public static void main(String[] args) {LinkedHashSet<Integer> linkedHashSet =new LinkedHashSet<>();linkedHashSet.add(10);linkedHashSet.add(20);linkedHashSet.add(15);Predicate<Integer> filter = null;linkedHashSet.removeIf(filter);System.out.println(linkedHashSet);}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Collection.removeIf(Collection.java:572)
No comments:
Post a Comment