Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java HashSet

Java HashSet

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

Example

Instantiate a HashSet named cars to store strings.

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

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

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<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, despite adding “BMW” twice, it only appears once in the set because each item in a set must be unique.

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

Use the remove() method to eliminate an item.

Example

cars.remove(“Volvo”);

To eliminate all items, employ the clear() method.

Example

cars.clear();

HashSet Size

To determine the number of items present, utilize the size() method.

Example

cars.size();

Loop Through a HashSet

Use a for-each loop to iterate through the elements of a HashSet.

Example

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

Other Types

Items in a HashSet are actually objects. In the examples above, we created items (objects) of type “String”. Remember that in Java, a String is an object, not a primitive type. To use other types, such as int, you must use the corresponding wrapper class, which is Integer. For other primitive types, use their respective wrapper classes: Boolean for boolean, Character for char, Double for double, and so on.

Example

Utilize a HashSet to store 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.");
      }
    }
  }
}