1. Introduction

Converting a List to a Set in Java is a common task, especially when we want to remove duplicate elements from a collection, as Set does not allow duplicates. In this blog post, we will learn how to convert a List to a Set using Java’s HashSet class, which is part of the Java Collections Framework.

2. Program Steps

1. Create a List with some elements, including duplicates.

2. Convert the List to a Set using the HashSet constructor.

3. Print the original List and the converted Set.

3. Code Program

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

public class ListToSet {

    public static void main(String[] args) {

        // Step 1: Create a List with some elements, including duplicates
        List<String> fruitList = Arrays.asList("Apple", "Banana", "Cherry", "Apple", "Banana");

        // Step 2: Convert the List to a Set using the HashSet constructor
        Set<String> fruitSet = new HashSet<>(fruitList);

        // Step 3: Print the original List and the converted Set
        System.out.println("Original List: " + fruitList);
        System.out.println("Set from List: " + fruitSet);
    }
}

Output:

Original List: [Apple, Banana, Cherry, Apple, Banana]
Set from List: [Banana, Cherry, Apple]

4. Step By Step Explanation

Step 1: We create a List named fruitList with some string elements, including duplicates.

Step 2: We convert fruitList to a Set using the HashSet constructor, which takes a collection as a parameter. The HashSet class is part of the Java Collections Framework and is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements the Set interface.

Step 3: We print the original fruitList and the converted fruitSet to observe that the duplicate elements from the List are eliminated in the Set, showcasing the uniqueness property of the Set collection type.