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]}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With