Java Convert ArrayList to HashSet

Tags: ArrayList HashSet

In this Java core tutorial we learn how to convert a java.util.ArrayList to a java.util.HashSet in Java programming language.

How to convert ArrayList to HashSet in Java

In Java, with a given ArrayList object we can use the HashSet(Collection<? extends E> c) constructor to create a new HashSet object from the ArrayList elements.

In the following Java program we show how to use this HashSet constructor to convert an ArrayList object to a HashSet object.

ConvertArrayListToSetExample1.java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConvertArrayListToSetExample1 {
    public static void main(String... args) {
        List<String> arrayList = new ArrayList<>();

        arrayList.add("Java");
        arrayList.add("Kotlin");
        arrayList.add("Groovy");

        Set<String> hashSet = new HashSet<>(arrayList);

        System.out.println("ArrayList: " + arrayList);
        System.out.println("HashSet: " + hashSet);
    }
}
The output as below.
ArrayList: [Java, Kotlin, Groovy]
HashSet: [Java, Groovy, Kotlin]

Happy Coding 😊

Java Convert ArrayList to Array

Java Convert ArrayList to String

Java Convert ArrayList to Comma Separated String

Java Convert ArrayList to LinkedList

Convert Array to List in Java

Java Create New Array with Class Type and Length

Java Create ArrayList using List Interface

Java Get Index of Minimum Value in ArrayList

How to use Java ArrayList with Examples

Java Convert Array to ArrayList

Java Insert Element to ArrayList at Specified Index

Java Get Minimum Value in ArrayList

How to Traverse ArrayList using Iterator in Java

How to Traverse ArrayList using for each loop in Java

How to Traverse ArrayList using forEach() method in Java

Java Add Element to ArrayList