首页 > 解决方案 > 根据条件合并两个列表并使用 java 8 将结果推送到地图

问题描述

我有两个列表源和目标想要根据某些条件合并它们并将数据推送到 Hashmap。我尝试了下面的代码,但我无法成功。

public List<Persona> fetchCommonPersonas(List<User> sourceList,
                                             List<User> targetList) {
final Map<String, String> map = new HashMap<>();
       map = sourceList.stream()
                .filter(source -> targetList.stream().anyMatch(destination -> {
                    if(destination.getAge().equals(source.getAge())) {
                        map.put(source.getUserId(), destination.getUserId());
                    }
                }
                ));    
}

标签: javalambda

解决方案


这是一种方法:

Map<String, String> map = 
    sourceList.stream()
              .map(source -> targetList.stream()
                                       .filter(dest -> dest.getUserId().equals(source.getUserId()))
                                       .map(dest -> new SimpleEntry<>(source.getPersonaId(), dest.getPersonaId()))
                                       .firstFirst())
              .filter(Optional::isPresent)
              .map(Optional::get)
              .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));   

您为源列表的每个元素找到目标列表的相应元素,将这些元素映射到Map.Entry包含两个人员 ID 的 a ,并将所有条目收集到 a Map


推荐阅读