将一个包含Set<Integer>元素的集合转换为列表嵌套列表。

4

我有一个 HashMap<Integer, Set<Integer>>

我想将地图中的集合Collection转换为列表List

例如:

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]]
         }
    }
3个回答

6
 map.values()
    .stream()
    .map(ArrayList::new)
    .collect(Collectors.toList());

你的开始不错:首先使用 map.values()。现在,如果你将它转换为一个流(stream),流中的每个元素都会是一个 Collection<Integer> (即每个单独的值);而你想将每个值转换为一个 List。在这种情况下,我提供了一个 ArrayList,它有一个接受 Collection 的构造函数,因此可以使用 ArrayList::new 方法引用。最后,所有这些被转换为 List 的单独的值都会通过 Collectors.toList() 被收集到一个新的 List 中。


4

不使用流的方法:

List<List<Integer>> listOfLists = new ArrayList<>(map.size());
map.values().forEach(set -> listOfLists.add(new ArrayList<>(set)));

3

Set<String>映射到ArrayList<String>,然后collect到一个列表中:

List<List<Integer>> result = map.values() // Collection<Set<String>>
                                .stream() // Stream<Set<String>>
                                .map(ArrayList::new) // Stream<ArrayList<String>>
                                .collect(toList()); // List<List<String>>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接