我想要的相反flatMap
。我有下面的代码:
List<String> list = Arrays.asList("A", "C", "B", "AA", "BB", "CC");
Stream<String> stream = list.stream();
Collection<List<String>> val = stream.sorted().collect(groupingBy(String::length)).values();
System.out.println("Values " + val);
这确实有效,但类型是Collection<List<String>>
. 我该怎么做List<List<String>>
?
我可以遍历Collection
或使用new Arraylist()
. 我正在寻找Arrays.asList
更简洁和不可变的东西。
如果我投我得到java.lang.ClassCastException
.
此外,这将对整个列表进行排序,然后进行分组。有没有办法先分组然后对较小的列表进行排序,这样效率会更高。
您可以流式传输值,然后收集到一个列表:
List<List<String>> values = list.stream()
.sorted()
.collect(groupingBy(String::length))
.values()
.stream()
.collect(toList());
但更好的方法是将结果传递给ArrayList
构造函数,如下所示:
List<List<String>> values = new ArrayList<>(list.stream()
.sorted().collect(groupingBy(String::length)).values());
如果要在分组后排序,则可以执行以下操作:
List<List<String>> values = new ArrayList<>(list.stream()
.collect(groupingBy(String::length))
.values());
values.forEach(Collections::sort);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句