List to MapList Java 8 Lambda的列表

时间:2018-01-18 20:37:52

标签: java lambda collections java-8 java-stream

我想用lambda将List<Map<Integer, List<Object>>>转换为Map<Integer, List<Object>>,但我完全迷失了,到目前为止我得到了这个;

public Map<Integer, List<Object>> getMapofList(List<Map<Integer, List<Object>>> listMaps) {

    return listMaps
            .stream()
            .filter(listMap -> listMap //Obtained Map
                    .entrySet()
                    .stream()
                    .filter(integerListEntry -> nonNull(integerListEntry.getValue())) //Check if there is a List<Object> not null
                    . //Not sure how to continue to finally just return a Map<Integer, List<Object>>
}

任何提示或帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

一个解决方案是:

return listMaps
        .stream()
        .flatMap(e -> e.entrySet()
                       .stream())
        .filter(e -> e.getValue() != null)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

或者如果可以有重复的密钥,那么您可以使用groupingBy收集器,如下所示:

return listMaps
         .stream()
         .flatMap(e -> e.entrySet()
                        .stream())
         .filter(e -> e.getValue() != null)
         .collect(Collectors.groupingBy(Map.Entry::getKey, 
               Collectors.mapping(Map.Entry::getValue, Collectors.toList())));