Create HashSet in Java

This example shows how to create a HashSet and adding elements to it in Java with an example.

Create HashSet in Java Example

package com.javaguides.collections.hashsetexamples;

import java.util.HashSet;

import java.util.Set;

public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        Set < String > daysOfWeek = new HashSet < > ();

        // Adding new elements to the HashSet
        daysOfWeek.add("Monday");
        daysOfWeek.add("Tuesday");
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored
        daysOfWeek.add("Monday");
        System.out.println(daysOfWeek);
    }
}

Output

[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]

Reference

Related Java HashSet Source Code Examples


Comments