Java 8 List to Set
Java 8 convert List to Set
- List
List integerList = Arrays.asList(1, 2, 3, 4, 5);
- List To Set : Implementation of set is hidden under the implementation which is HashSet
Set integerSet = integerList.stream().collect(Collectors.toSet());
1
2
3
4
5
[addToAppearHere]
- To Retrieve a specific Implementation of Hash Set
In this example we retrieve LinkedHashSet
LinkedHashSet set1 = integerList.stream()
.collect(
LinkedHashSet::new,
(objects, integer) -> ((Set)objects).add(integer),
(objects, objects2) -> ((Set)objects).addAll(objects2)
);
set1.stream().forEach(System.out::println);
1
2
3
4
5