• Java program to convert list to set.
  • Convert ArrayList of string to HashSet in java example program
  • How to convert List to Set in java 
  • Set<String> strSet = new HashSet<String>(arrList);
  • HashSet having a constructor which will take list as an argument.
  • Lets see how to convert list to Set using java program.



#1: Java Example Program to Convert List to Set.


  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = new HashSet<String>(arrList);
  18. System.out.println(strSet);

  19. }

  20. }

Output:

  1. [Java, Example Program, List to String]

  • Using java.util.stream we can convert List to set in java 8
  • We can use java 8 java.util.stream.Collectors
  • arrList.stream().collect(Collectors.toSet());

#2: Java Example program to convert List to Set using java 8.

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Set;
  4. import java.util.stream.Collectors;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = arrList.stream().collect(Collectors.toSet());
  18. System.out.println(strSet);

  19. }

  20. }


Output:

java convert list to set

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu