Map.computeIfPresent()初始化Java中的列表

时间:2018-08-23 17:57:46

标签: java java-8 maps

我有以下代码:

for (String val: values) {
     EnumType type = EnumType.get(val);
     if (type != null) {
         String key = type.name();
         if (key.equals("camp2"))
                key = "camp1";
         ArrayList<String> tempList= mapN.get(key); //1
         if (tempList == null) {  // 2
            tempList = new ArrayList<>();
         }
         tempList.add(val);
         mapN.put(key, tempList);  //3
    }
}

其中mapN和有效值是:

private Map<String, ArrayList<String>> mapN
ArrayList<String>  values
type is an enum 

我有声纳,声纳告诉我在// // 1,2,3的值中,我需要使用:

Map.computeIfPresent()

但是我已经阅读了有关此主题的内容,但没有找到更改代码的方法。

谁可以帮助我?

2 个答案:

答案 0 :(得分:1)

我想您可以将其缩短为:

values.forEach(val -> {
     EnumType type = EnumType.get(val);
     if(type != null){
          String key = type.name();
          if (key.equals("camp2"))
               key = "camp1";
          mapN.computeIfAbsent(key, x -> new ArrayList<>()).add(val);
     }
});

答案 1 :(得分:0)

@Eugene答案的修改版本:

values.forEach(val -> Optional.of(val)
   // get corresponding type, if it exists
   .map(EnumType::get)
   // get key
   .map(EnumType::name)
   // handle key == "camp2" scenario
   .map(key -> key.equals("camp2")
     ? "camp1"
     : key
   )
   // add val to map value list
   .ifPresent(key -> mapN.computeIfAbsent(
     key,
     x -> new ArrayList<>()
   ).add(val))
});