如何在流中收集到TreeMap中? [英] How to collect into TreeMap in stream?
问题描述
我在Stream中有两个Collectors.groupingBy
.而且我需要将所有信息收集到TreeMap
.
I have two Collectors.groupingBy
in Stream. And I need to collect all information to TreeMap
.
我的代码:
Map<LocalDate, Map<String, List<RollingField>>> fieldMap = rollingFields.stream().collect(
Collectors.groupingBy(
RollingField::getDate,
Collectors.groupingBy(fi -> fi.getMeta().getName())));
然后返回HashMap
.我需要添加什么来返回TreeMap
?我需要此内容以按LocalDate
进行排序.
And this return HashMap
. What i need to add for returning TreeMap
? I need this for sorting by LocalDate
.
推荐答案
Use the specific method that allows to provide a Map
factory through Supplier
that is
Collectors.groupingBy(Function<..> classifier, Supplier<M> mapFactory, Collector<..> downstream)
where:
-
classifier
将元素映射到键中 -
mapFactory
产生一个新的空地图(在这里使用() -> new TreeMap<>()
) -
downstream
下游减排量
classifier
maps elements into keysmapFactory
produces a new empty map (here you use() -> new TreeMap<>()
)downstream
the downstream reduction
实施:
Map<LocalDate, Map<String, List<RollingField>>> fieldMap = rollingFields.stream().collect(
Collectors.groupingBy(
RollingField::getDate, // outer Map keys
TreeMap::new, // outer Map is TreeMap
Collectors.groupingBy( // outer Map values
fi -> fi.getMeta().getName(), // inner Map keys
TreeMap::new, // inner Map is TreeMap
Collectors.toList() // inner Map values (default)
)
));
不用担心没有downstream
的重载方法,例如Collectors.groupingBy(Function<..> classifier, Supplier<M> mapFactory)
. downstream
的默认实现是从
Don't worry that there is no such overloaded method like Collectors.groupingBy(Function<..> classifier, Supplier<M> mapFactory)
without downstream
. The default implementation of downstream
is collecting to List, therefore free to reuse it (Collectors.toList()
), from the JavaDoc:
这会产生类似于以下内容的结果:
groupingBy(classifier, toList());
这篇关于如何在流中收集到TreeMap中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!