Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
152 views
in JAVA by (178k points)
How do I remove elements from a HashSet in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

To remove elements from a HashSet in Java, you can use the remove() method of the HashSet class. The remove() method removes the specified element from the set if it is present. 

Here's an example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> set = new HashSet<>();

        // Add elements to the HashSet
        set.add("apple");
        set.add("banana");
        set.add("cherry");
        set.add("orange");

        // Print the HashSet
        System.out.println("HashSet before removing an element: " + set);

        // Remove an element from the HashSet
        set.remove("banana");

        // Print the HashSet after removing an element
        System.out.println("HashSet after removing an element: " + set);
    }
}
 

In this example, we create a HashSet of strings and add some elements to it. We then remove the element "banana" using the remove() method and print the HashSet before and after removing the element. 

The output of the above code will be:

HashSet before removing an element: [orange, apple, cherry, banana]
HashSet after removing an element: [orange, apple, cherry]
 

As you can see, the element "banana" has been removed from the HashSet.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...