Convert List to Set in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our list with string values −

List<String> list = Arrays.asList("Jacob", "Kiya", "Bradley", "Tom", "Jamie");

Now, convert the above list to set −

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

Example

Following is the program to convert List to Set in Java −

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String args[]) {
      List<String> list = Arrays.asList("Jacob", "Kiya", "Bradley", "Tom", "Jamie");
      System.out.println("List = " + list);
      Set<String> set = new HashSet<String>(list);
      System.out.println("Set (converted from list) = " + set);
   }
}

Output

List = [Jacob, Kiya, Bradley, Tom, Jamie]
Set (converted from list) = [Jamie, Tom, Bradley, Kiya, Jacob]
raja
Published on 25-Sep-2019 07:52:19
Advertisements