如何在流中收集到TreeMap中? [英] How to collect into TreeMap in stream?

查看:176
本文介绍了如何在流中收集到TreeMap中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

推荐答案

使用允许通过Supplier通过
提供Map工厂的特定方法.

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 keys
  • mapFactory 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆