java8映射如何简单地将一些元素添加到列表值 [英] java8 map how to add some element to a list value simply

查看:104
本文介绍了java8映射如何简单地将一些元素添加到列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Map<String, List<String>>录制某些内容,例如 每个城市都有多少种用户.

I want to use Map<String, List<String>> to record something, e.g. each city have how many users of some kind .

现在我的代码是

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

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

but I feel it's a little cumbersome, I want this effect

    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>

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

So have any other manner could simplify it?

推荐答案

使用computeIfAbsent:

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

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

Which stores a new list in the map if it does not already exist and returns the new or existing list.

这篇关于java8映射如何简单地将一些元素添加到列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆