Can we convert a list to a Set in Java?

JavaObject Oriented ProgrammingProgramming

We can convert a list into a set easily using Set's constructor. We need to pass the list to the constructor.

Syntax

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

In case, list contains the duplicate values, set will remove them and will keep only unique values.

Example

The following example shows how to convert a list into set.

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) {

      // Create a list object
      List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "C"));

      // print the list
      System.out.println(list);
      Set<String> set = new HashSet<String>(list);
      System.out.println(set);
   }
}

Output

This will produce the following result −

[A, B, C, C]
[A, B, C]
raja
Updated on 09-May-2022 11:36:03

Advertisements