# How to convert a List to a Set in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 8, 2019, updated Oct 29, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/how-to-convert-a-list-to-a-set-in-java

> A protip to convert a list object (ArrayList) to a set object (HashSet) and vice versa in Java.

Since both `Set` and `List` extend the `Collection` interface, the conversion is simple. All you need to do is pass a list to a set constructor while initializing or vice versa:

```java
// convert list to set
Set set = new HashSet(list);

// convert set to list
List list = new ArrayList(set);
```

## Convert a List to a Set in Java

Apart from constructor initialization, we can also use Java 8 Streams for a list to a set conversion:

```java
// create a list
List<String> list = new ArrayList<>(Arrays.asList("?", "?", "?", "?", "?"));

// 1st method - constructor initialization
Set<String> set = new HashSet<>(list);

// 2nd method - using `set.addAll()`
Set<String> set2 = new HashSet<>();
set2.addAll(list);

// 3rd method - using Java 8 Streams
Set<String> set3 = list.stream().collect(Collectors.toSet());

// print values
for (String str : set3) {
    System.out.println(str);
}
// ?
// ?
// ?
// ?
```

Since set collection only allows unique values, all duplicate values from the list will be removed.

## Convert a Set to a List in Java

```java
// create a set
Set<String> set = new HashSet<>(Arrays.asList("?", "?", "?", "?", "?"));

// 1st method - constructor initialization
List<String> list = new ArrayList<>(set);

// 2nd method - using `set.addAll()`
List<String> list2 = new ArrayList<>();
list2.addAll(list);

// 3rd method = using Java 8 Streams
List<String> list3 = set.stream().collect(Collectors.toList());

// print values
for (String str : list3) {
    System.out.println(str);
}
// ?
// ?
// ?
// ?
```

Notice the output. When we first initialized the set, it removed all duplicate values and only kept unique strings.
