【问题标题】:EnumMap & streams枚举映射和流
【发布时间】:2016-09-10 14:06:31
【问题描述】:

您好试图弄清楚如何映射到 EnumMap 但没有成功。 目前我分两步进行,创建地图,然后将其设为 EnumMap。 问题是。

  1. 是否可以一步完成?
  2. 从效率的角度来看,从中获取价值会更好 输入,使它们成为一个集合,然后将其流式传输,或者仅使用 toMap 作为 它现在是正确的。谢谢

    Map<CarModel, CarBrand> input...  
    final Map<CarBrand, CarsSellers> ret = input.values()
                .stream().filter(brand -> !brand.equals(CarBrand.BMW))
                .collect(toMap(Function.identity(), brand -> new CarsSellers(immutableCars, this.carsDb.export(brand))));
    
     final EnumMap<CarBrand, CarsSellers> enumMap = new EnumMap<>(CarBrand.class);
        enumMap.putAll(ret);
    

【问题讨论】:

    标签: java collections enums java-8 java-stream


    【解决方案1】:

    TL;DR:您需要使用other toMap method

    默认情况下,toMap 使用 HashMap::new 作为 Supplier&lt;Map&gt; - 您需要提供一个新的 EnumMap

    final Map<CarBrand, CarsSellers> ret = input.values()
            .stream()
            .filter(brand -> brand != CarBrand.BMW)
            .collect(toMap(
                    identity(),
                    brand -> new CarsSellers(immutableCars, this.carsDb.export(brand)),
                    (l, r) -> {
                        throw new IllegalArgumentException("Duplicate keys " + l + "and " + r + ".");
                    },
                    () -> new EnumMap<>(CarBrand.class)));
    

    参数是:

    1. key 提取器
    2. value 提取器
    3. 一个“mergeFunction”,它接受两个值,一个已经存在于Map 中,另一个要添加。在这种情况下,我们只需抛出一个IllegalArgumentException,因为键应该是唯一的
    4. “地图供应商” - 这会返回一个新的EnumMap

    代码注释:

    1. 程序到interface - Map 不是EnumMap
    2. enum 是单例的,所以你可以使用a != Enum.VALUE
    3. import static for Function.identity() 让事情变得不那么冗长

    【讨论】:

    • 感谢您的帮助,我读到 forloops 比流更有效。当我们谈论 toMap 时,它是否适用,如果我使用 for 来做同样的事情。会更快吗?
    • @Hook 与 Java 很难说微优化是否会更快。一个普通的循环很可能更快,因为移动部件要少得多。我建议您熟悉 jmh 并为您的确切代码获得明确的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多