Languages
[Edit]
EN

Java - iterate over Set and remove indicated items

0 points
Created by:
Jax-Cano
328

In this article, we would like to show you how to iterate over Set and remove indicated items in Java.

 

1. Using iterator

In this example, we use an iterator to remove indicated item from the letters HashSet.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        Set<String> letters = new HashSet<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        Iterator<String> iterator = letters.iterator();

        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("A")) {
                iterator.remove();
            }
        }

        System.out.println(letters);
    }
}

Output:

[B, C]

2. Using Collection.removeIf()

In this example, we use Java 8 removeIf() method to remove indicated element from the letters HashSet.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        Set<String> letters = new HashSet<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        letters.removeIf(element -> element.equals("A"));

        System.out.println(letters);
    }
}

Output:

[B, C]

3. Using stream

In this example, we create an instance of a stream from the letters HashSet, filter each element and collect the result in the new filteredLetters.

import java.util.*;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {
        Set<String> letters = new HashSet<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        Set<String> filteredLetters = letters
                .stream()
                .filter(element -> !element.equals("A"))
                .collect(Collectors.toSet());

        System.out.println(filteredLetters);
    }
}

Output:

[B, C]
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join