EnumMap和流

Hoo*_*ook 4 java collections enums java-8 java-stream

嗨试图找出如何映射到EnumMap没有成功.目前我正在分2步完成,我创建了地图,然后我将其设为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);
    
    Run Code Online (Sandbox Code Playgroud)

Bor*_*der 13

TL; DR:您需要使用其他toMap方法.

默认情况下toMap使用HashMap::newSupplier<Map>-你需要提供一个新的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)));
Run Code Online (Sandbox Code Playgroud)

参数是:

  1. key提取
  2. value提取
  3. 一个"mergeFunction",它带有两个值,一个已经存在Map,另一个要添加.在这种情况下,我们只是抛出一个IllegalArgumentException因为键应该是唯一的
  4. "地图供应商" - 这将返回一个新的EnumMap.

您的代码注释:

  1. 程序到interface- Map不是EnumMap
  2. enum 是单身,所以你可以使用 a != Enum.VALUE
  3. 一个import static用于Function.identity()使事情变得更简洁