Create LinkedHashSet in Java Example

 This simple Java example shows how to create and add elements to LinkedHashSet in Java.

The LinkedHashSet class provides add() to add elements to LinkedHashSet in Java.

Create LinkedHashSet in Java Example

package com.javaguides.collections.linkedhashsetexamples;

import java.util.LinkedHashSet;

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

        // 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, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]

Comments