使用Java 8 API将键-值对象对列表转换为简单的Multimap [英] Convert List of key - value Object pairs to simple Multimap using Java 8 API

查看:60
本文介绍了使用Java 8 API将键-值对象对列表转换为简单的Multimap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有键值列表:

public class KeyValue {

    private Long key;

    private Long value;

    public KeyValue(long key, long value) {
        this.key = key;
        this.value = value;
    } 

    //getters, setters, toStrings...
}

...

    List<KeyValue> values = new ArrayList<>();
    values.add(new KeyValue(15, 10));
    values.add(new KeyValue(15, 12));
    values.add(new KeyValue(25, 13));
    values.add(new KeyValue(25, 15));

如何使用Java 8 API将其转换为Multimap?

How to convert it to Multimap using Java 8 API?

程序方式:

    Map<Long, List<Long>> keyValsMap = new HashMap<>();
    for (KeyValue dto : values) {
        if (keyValsMap.containsKey(dto.getKey())) {
            keyValsMap.get(dto.getKey()).add(dto.getValue());
        } else {
            List<Long> list = new ArrayList<>();
            list.add(dto.getValue());
            keyValsMap.put(dto.getKey(), list);
        }
    }

结果:

{25 = [13,15],15 = [10,12]}

{25=[13, 15], 15=[10, 12]}

推荐答案

这正是

This is exactly what the groupingBy collector allows you to do:

Map<Long, List<Long>> result = values.stream()
     .collect(Collectors.groupingBy(KeyValue::getKey,
         Collectors.mapping(KeyValue::getValue, Collectors.toList())));

然后

Then the mapping collector converts the KeyValue objects into their respective values.

这篇关于使用Java 8 API将键-值对象对列表转换为简单的Multimap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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