There are following way to convert Array to List and Set in Java.
Convert Array to Set :-
- The set interface is an unordered collection of objects in which duplicate values cannot be stored.
- In first way, we pass the Array as parameter in the set constructor with the help of Arrays.asList () method.
- Return String type set and print the data.
- In Second way, we are stream the Array data from Arrays.asList() method then convert in set from Collectors.toSet() method.
- Return String type set and print the data.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class ConvertArrayToSet {
public static void main(String[] args) {
String s[] = { "java", "Spring", "Hibernate", "java" };
// from Arrays.asList method
Set st = new HashSet(Arrays.asList(s));
System.out.println("Arrays.asList method output :- " + st);
Set data = Arrays.asList(s).stream().collect(Collectors.toSet());
System.out.println("from java 8 list method value :- " + data);
}
}
Output :-
Arrays.asList method output :- [Hibernate, java, Spring]
from java 8 list method value :- [Hibernate, java, Spring]
Convert Array to List :-
- The List interface is an unordered collection of objects in which duplicate values can be stored.
- In First Way, we convert Array to list from asList() method because it is internally call new ArrayList() class.
Syntax:- public static <T> List<T> asList(T… a) { return new ArrayList<>(a); }
- Return String type set and print the data.
- In Second way, we create one empty ArrayList Object.
- From forEach() method we iterate Array data one by one and add to list.
- Return String type set and print data.
- In Third way, we are stream the Array data from Arrays.asList() method then convert in List from toList() method.
- Return String type List and print the data.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConvertArrayToList {
public static void main(String[] args) {
String s[] = { "java", "Spring", "Hibernate", "java" };
// first way from Arrays.asList method
List list = Arrays.asList(s);
System.out.println("Arrays.asList method output :- " + list);
// second way from forEach and list add method
List addList = new ArrayList();
for (String st : s) {
addList.add(st);
}
System.out.println("from forEach and list add method :- " + addList);
// third way from java8 list method
List data = Arrays.asList(s).stream().collect(Collectors.toList());
System.out.println("from java 8 list method value :- " + data);
}
}
Output :-
Arrays.asList method output :- [java, Spring, Hibernate, java]
from forEach and list add method :- [java, Spring, Hibernate, java]
from java 8 list method value :- [java, Spring, Hibernate, java]