Java HashSet


Java HashSet

HashSet is a collection of items where everything is different, and is available in the java.util package:


Example

Create a HashSet object called cars that will store strings:

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

            HashSet<String> cars = new HashSet<String>();
            


Add Items

The HashSet section has many useful features. 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<String> cars = new HashSet<String>();
                cars.add("Volvo");
                cars.add("BMW");
                cars.add("Ford");
                cars.add("BMW");
                cars.add("Mazda");
                System.out.println(cars);
              }
            }
            

Note: In the example above, although the BMW has been added twice it appears only once in the set because everything in the set must be different.


Check If an Item Exists

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


Example
cars.contains("Mazda");
        


Remove an Item

To remove an item, use the remove() method:


Example
cars.remove("Volvo");
        

To delete all items, use the clear() method:


Example
cars.clear();
        


HashSet Size

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


Example
cars.size();
        


Loop Through a HashSet

Check the HashSet items for-each loop:


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


Other Types

The items in the HashSet are actually objects. In the examples above, we created "String" type objects. Remember that String in Java is an object (not an old version). To use other types, such as int, you must specify an equal wrapper category: Integer. For other classic types, use: Boolean boolean, Character for Character, Double for double, etc:


Example

Use a HashSet that stores Integer objects:

import java.util.HashSet;

            public class Main {
              public static void main(String[] args) {
            
                // Create a HashSet object called numbers
                HashSet<Integer> numbers = new HashSet<Integer>();
            
                // Add values to the set
                numbers.add(4);
                numbers.add(7);
                numbers.add(8);
            
                // Show which numbers between 1 and 10 are in the set
                for(int i = 1; i <= 10; i++) {
                  if(numbers.contains(i)) {
                    System.out.println(i + " was found in the set.");
                  } else {
                    System.out.println(i + " was not found in the set.");
                  }
                }
              }
            }