英文:
How to collect into TreeMap in stream?
问题
我在Stream中有两个Collectors.groupingBy
。我需要将所有信息收集到TreeMap
中。
我的代码:
Map<LocalDate, Map<String, List<RollingField>>> fieldMap = rollingFields.stream().collect(
Collectors.groupingBy(
RollingField::getDate,
Collectors.groupingBy(fi -> fi.getMeta().getName())));
而这会返回HashMap
。我需要添加什么来返回TreeMap
?我需要这样做来按LocalDate
进行排序。
英文:
I have two Collectors.groupingBy
in Stream. And I need to collect all information to TreeMap
.
My Code:
Map<LocalDate, Map<String, List<RollingField>>> fieldMap = rollingFields.stream().collect(
Collectors.groupingBy(
RollingField::getDate,
Collectors.groupingBy(fi -> fi.getMeta().getName())));
And this return HashMap
. What i need to add for returning TreeMap
? I need this for sorting by LocalDate
.
答案1
得分: 3
使用特定的方法,允许通过Supplier
提供一个Map
工厂,该方法是Collectors.groupingBy(Function<..> classifier, Supplier<M> mapFactory, Collector<..> downstream)
,其中:
classifier
将元素映射到键mapFactory
生成一个新的空映射(在这里使用() -> new TreeMap<>()
)downstream
下游规约操作
实现示例:
Map<LocalDate, Map<String, List<RollingField>>> fieldMap = rollingFields.stream().collect(
Collectors.groupingBy(
RollingField::getDate, // 外层映射的键
TreeMap::new, // 外层映射为 TreeMap
Collectors.groupingBy( // 外层映射的值
fi -> fi.getMeta().getName(), // 内层映射的键
TreeMap::new, // 内层映射为 TreeMap
Collectors.toList() // 内层映射的值(默认)
)
)
));
不用担心没有像Collectors.groupingBy(Function<..> classifier, Supplier<M> mapFactory)
这样不带downstream
参数的重载方法。downstream
的默认实现是收集到List中,因此可以自由地重用它(Collectors.toList()
),来自JavaDoc:
> 这产生的结果类似于:groupingBy(classifier, toList());
英文:
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
maps elements into keysmapFactory
produces a new empty map (here you use() -> new TreeMap<>()
)downstream
the downstream reduction
Implementation:
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)
)
));
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:
> This produces a result similar to: groupingBy(classifier, toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论