Convert List of key - value Object pairs to simple Multimap using Java 8 API

MGorgon :

Having list of key - values:

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

How to convert it to Multimap using Java 8 API?

Procedural way:

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

Result:

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

Jorn Vernee :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442911&siteId=1