Java Code Example: simple HashSet Example

This code creates a HashSet of strings and adds three elements to it: “apple”, “banana”, and “orange”. It then prints out the contents of the HashSet, checks if “apple” is present in the HashSet, removes “banana” from the HashSet, and prints out the contents of the HashSet again. Finally, it iterates over the elements in the HashSet and prints each element.

import java.util.HashSet;

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

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

        // Printing the HashSet
        System.out.println(set);

        // Checking if an element is present in the HashSet
        if (set.contains("apple")) {
            System.out.println("The HashSet contains apple.");
        } else {
            System.out.println("The HashSet does not contain apple.");
        }

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

        // Printing the HashSet after removing an element
        System.out.println(set);

        // Iterating over the elements in the HashSet
        for (String element : set) {
            System.out.println(element);
        }
    }
}