Languages
[Edit]
EN

Java - clear HashSet

0 points
Created by:
Dirask Community
6360

In this article, we would like to show you how to clear the HashSet in Java.

Quick solution:

myHashSet.clear();

 

Practical example

In this example, we use clear() method to remove all items from the letters HashSet.

package hashsetOperations;

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");

        System.out.println("Before: " + letters);  // [A, B, C]

        letters.clear();                           // removes all items

        System.out.println("After:  " + letters);  // []
    }
}

Output:

Before: [A, B, C]
After:  []

Java Collections - HashSet

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