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

前端 未结 1 718
甜味超标
甜味超标 2020-12-11 04:22

Having list of key - values:

public class KeyValue {

    private Long key;

    private Long value;

    public KeyValue(long key, long value) {
        thi         


        
1条回答
  •  一向
    一向 (楼主)
    2020-12-11 04:58

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

    Map> 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.

    0 讨论(0)
提交回复
热议问题