Can we convert a List to Set and back in Java?


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

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

On similar pattern, we can get a list from a set using its constructor.

List<Integer> list = new ArrayList<Integer>(set);

Example

Following is the example showing the conversion of list to set and set to list −

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,3,3,4,5));
      System.out.println("List: " + list);
      Set<Integer> set = new HashSet<>(list);
      System.out.println("Set: " + set);
      List<Integer> list1 = new ArrayList<Integer>(set);
      System.out.println("List: " + list1);
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 3, 3, 4, 5]
Set: [1, 2, 3, 4, 5]
List: [1, 2, 3, 4, 5]

Updated on: 09-May-2022

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements