- 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.
- package com.instanceofjava;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.Set;
- public class ListToSet {
- /**
- * @author www.Instanceofjava.com
- * @category interview questions
- *
- * Description: Convert List to set in java with example program
- *
- */
- public static void main(String[] args) {
- ArrayList<String> arrList= new ArrayList<>();
- arrList.add("Java");
- arrList.add("List to String");
- arrList.add("Example Program");
- Set<String> strSet = new HashSet<String>(arrList);
- System.out.println(strSet);
- }
- }
Output:
- [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.
- package com.instanceofjava;
- import java.util.ArrayList;
- import java.util.Set;
- import java.util.stream.Collectors;
- public class ListToSet {
- /**
- * @author www.Instanceofjava.com
- * @category interview questions
- *
- * Description: Convert List to set in java with example program
- *
- */
- public static void main(String[] args) {
- ArrayList<String> arrList= new ArrayList<>();
- arrList.add("Java");
- arrList.add("List to String");
- arrList.add("Example Program");
- Set<String> strSet = arrList.stream().collect(Collectors.toSet());
- System.out.println(strSet);
- }
- }
Output:
No comments