Java convert List to Set

This is example of java program we will see ho to convert list to set. We use List to keep order of the element which are added. On the other hand Java Set does not keep the elements in order and also does not keep duplicate elements.

Our program let’s created duplicated elements and add them to list. Then create Set with HashSet constructor which accept Collection. You can see example how duplicates can be removed by printing the elements of the set. Pay attention that the order is not no guaranteed. If you need to preserve the order you can use LinkedHashSet instead of HashSet.

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

public class MainConvertListToSet {
    public static void main(String[] args) {
        List<String> list = List.of("A", "A", "B", "B", "C", "D");
        // print list
        System.out.println("Print list: " + list);

        // Use HastSet constructor which accept java.util.Collection
        Set<String> set = new HashSet<>(list);
        // print set
        System.out.println("Print set: " + set);
    }
}

Output:

Print list: [A, A, B, B, C, D]
Print set: [A, B, C, D]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.