HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java HashSet

A HashSet is a collection of items where every item is unique, and it is found in the java.util package:



Create a HashSet object called cars that will store strings:

Example
    
  import java.util.HashSet; // Import the HashSet class

HashSet cars = new HashSet();
             

Add Items

The HashSet class has many useful methods. For example, to add items to it, use the add() method:

Example
    
    // Import the HashSet class
    import java.util.HashSet;
    
    public class Main {
      public static void main(String[] args) {
        HashSet cars = new HashSet();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        cars.add("BMW");
        cars.add("Mazda");
        System.out.println(cars);
      }
    }
                 

Check If an Item Exists

To check whether an item exists in a HashSet, use the contains() method:

Example
    
  cars.contains("Mazda")
             

Remove an Item

To remove an item, use the remove() method and refer to the key:

Example
    
  cars.remove("Volvo");
             

HashSet Size

To find out how many items there are, use the size method:

Example
    
 cars.size();
             

Loop Through a HashSet

Loop through the items of an HashSet with a for-each loop



Create a HashMap object called capitalCities that will store String keys and String values:

Example
    
                
             
 for (String i : cars) {
  System.out.println(i);
 }