zak*_*zak 4 java collections list set java-stream
我有一个 HashMap<Integer, Set<Integer>>.
我想将Collection地图中的集合转换为列表列表.
例如:
import java.util.*;
import java.util.stream.*;
public class Example {
public static void main( String[] args ) {
Map<Integer,Set<Integer>> map = new HashMap<>();
Set<Integer> set1 = Stream.of(1,2,3).collect(Collectors.toSet());
Set<Integer> set2 = Stream.of(1,2).collect(Collectors.toSet());
map.put(1,set1);
map.put(2,set2);
//I tried to get the collection as a first step
Collection<Set<Integer>> collectionOfSets = map.values();
// I neeed List<List<Integer>> list = ......
//so the list should contains[[1,2,3],[1,2]]
}
}
Run Code Online (Sandbox Code Playgroud)
map.values()
.stream()
.map(ArrayList::new)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
你的开始很好:map.values()开始吧.现在,如果你流式传输,Stream中的每个元素都将是一个Collection<Integer>(每个单独的值); 并且您希望将每个值转换为a List.在这种情况下,我提供了一个ArrayList具有接受a的构造函数Collection,因此ArrayList::new方法引用用法.最后,所有那些每个单独的值(一旦转换为a List)被收集到一个新的ListviaCollectors.toList()