2016-05-14 57 views
3

嗨試圖找出如何映射到EnumMap沒有成功。 目前我正在做2個步驟,我創建了地圖,然後將其製作爲EnumMap。 問題是。EnumMap&streams

  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); 
    

回答

8

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

默認情況下,toMap使用HashMap::new作爲Supplier<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))); 

參數是:

  1. key提取
  2. value提取
  3. 一個 「組合器」,它有兩個值,一個已經存在於所述Map和一個要被添加。在這種情況下,我們只需要輸入IllegalArgumentException作爲密鑰應該是唯一的
  4. 「地圖供應商」 - 這將返回一個新的EnumMap。您的代碼

注:

  1. 程序到interface - MapEnumMap
  2. enum是單身,所以你可以使用a != Enum.VALUE
  3. import staticFunction.identity()使事情少詳細
+0

感謝您的幫助,我發現forloops比stream更高效。它是否適用於我們正在談論的地圖時,如果我使用相同的方法來代替。它會更快嗎? – Hook

+0

@與Java掛鉤很難說微型優化是否會更快。由於移動部件少得多,所以簡單的循環很可能會更快。我建議你熟悉一下[jmh](http://openjdk.java.net/projects/code-tools/jmh/),併爲你的確切代碼得到明確的答案。 –