计算地图-将元素添加到现有列表或创建新列表并添加到其中 [英] Compute map - add element to existing List or create new List and add to it

查看:117
本文介绍了计算地图-将元素添加到现有列表或创建新列表并添加到其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

private static void computeMapAddition(Map<String, List<XXX>> objectMap,
    XXX objectToAdd, String key) {
    if (objectMap.containsKey(key)) {
        List<XXX> objectList = objectMap
            .get(key);
        objectList.add(objectToAdd);
    } else {
        List<XXX> objectList = new ArrayList<>();
        objectList.add(objectToAdd);
        objectMap.put(key, objectList);
    }
}

此代码的作用:

1)如果map包含键,则检索值-即List-并将元素添加到该列表(它可以已经有很多元素)

1) if map contains key then retrieve value - which is List - and add element to that list (it can have lots of elements already)

2)如果地图不包含键,则创建新列表,将元素添加到新创建的列表中,然后将该元素(键,值)放入地图中

2) if map doesn't contain a key then create new list, add element to the newly created list and put that (key, value) to the map

有什么方法可以使Java 8不再那么冗长?

Is there any way to make it less verbose using Java 8?

推荐答案

java 8已添加

java 8 added computeIfAbsent to Map interface. It does exactly what you want:

// return the list if already present or make a new one, insert into the map 
// and return the newly created one
List<XXX> objectList = objectMap.computeIfAbsent(key, k -> new ArrayList<>());

// add new object to list
objectList.add(objectToAdd);

或者您也可以将其组合为

Or you can combine it together as

objectMap.computeIfAbsent(key, k -> new ArrayList<>()).add(objectToAdd);

这篇关于计算地图-将元素添加到现有列表或创建新列表并添加到其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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