HashSet removeIf(Predicate) in Java

removeIf(Predicate): This method is available in java.util.HashSet class of Java.

Syntax:

boolean java.util.Collection.removeIf(Predicate<? super String> 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 exceptions

Java

import java.util.HashSet;
import java.util.function.Predicate;

public class HashSetremoveIf {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        Predicate<? super String> filter = k -> k.equals("Java");
        hashSet.removeIf(filter);

        System.out.println(hashSet);
    }
}

Output:

[C++, Hello]


Approach 2: NullPointerException

Java

import java.util.HashSet;
import java.util.function.Predicate;

public class HashSetremoveIf {
    public static void main(String[] args) {

        HashSet<String> hashSet = new HashSet<String>();

        hashSet.add("Hello");
        hashSet.add("Java");
        hashSet.add("C++");
        hashSet.add("Hello");

        Predicate<? super String> filter = null;
        hashSet.removeIf(filter);

        System.out.println(hashSet);
    }
}

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