Languages
[Edit]
EN

Java - retain from HashSet (retainAll())

0 points
Created by:
Dirask Community
6360

In this article, we would like to show you how to retain from HashSet all of its elements that are contained in the specified collection in Java.

Quick solution:

myHashSet1.retainAll(myHashSet2);

 

Practical example

In this example, we have two HashSets: letters1 and letters2. Using retainAll() method we remove elements from letters1 and retain only elements contained in letters2.

import java.util.*;

public class Example {

    public static void main(String[] args) throws NullPointerException {
        Set<String> letters1 = new HashSet<>();
        letters1.add("A");
        letters1.add("B");
        letters1.add("C");
        letters1.add("D");
        letters1.add("E");


        System.out.println("Before retainAll(): " + letters1);

        Set<String> letters2 = new HashSet<>();
        letters2.add("A");
        letters2.add("B");
        letters2.add("C");

        letters1.retainAll(letters2);  // retain elements from letters2

        System.out.println("After retainAll():  " + letters1);
    }
}

Output:

Before retainAll(): [A, B, C, D, E]
After retainAll():  [A, 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