How can we convert list to Set in Java?


A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values.

Set<String> set = new HashSet<>(list);

Or we can use set.addAll() method to add all the elements of the list to the set.

set.addAll(list);

Using streams as well, we can get a set from a list.

set = list.stream().collect(Collectors.toSet());

Example

Following is the example showing the list to set conversion via multiple ways −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "D"));
      System.out.println("List: " + list);
      Set<String> set = new HashSet<>(list);
      System.out.println("Set: " + set);
      set = new HashSet<>();
      set.addAll(list);
      System.out.println("Set: " + set);
      set = new HashSet<>();
      set = list.stream().collect(Collectors.toSet());
      System.out.println("Set: " + set);
   }
}

Output

This will produce the following result −

List: [A, B, C, D, D]
Set: [A, B, C, D]
Set: [A, B, C, D]
Set: [A, B, C, D]

Updated on: 22-Oct-2023

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements