【问题标题】:java8 map how to add some element to a list value simply [duplicate]java8映射如何简单地将一些元素添加到列表值[重复]
【发布时间】:2016-05-11 14:38:04
【问题描述】:

我想用Map<String, List<String>> 记录一些东西,例如 每个城市都有多少用户。

现在我的代码是

    Map<String, List<String>> map = new HashMap<>();
    if(map.get("city_1")==null){
        map.put("city_1", new ArrayList<>());
    }
    map.get("city_1").add("aaa");

但我觉得有点麻烦,我想要这个效果

    Map<String, List<String>> map = new HashMap<>();
    map.compute("city_1", (k,v)->v==null?new ArrayList<>():v.add("aaa"));

但它有编译错误:

Type mismatch: cannot convert from boolean to List<String>

那么还有其他方法可以简化吗?

【问题讨论】:

    标签: java-8


    【解决方案1】:

    使用computeIfAbsent:

    map.computeIfAbsent(work, k -> new ArrayList<>()).add("aaa");
    

    如果新列表尚不存在,则将新列表存储在地图中并返回新列表或现有列表。

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2021-12-02
      • 2022-11-17
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2014-03-22
      • 2018-11-13
      相关资源
      最近更新 更多