JAVA8的Lambda遍历两个List匹配数据方法

1. 定义一个静态方法

/**
     *  通过遍历两个List中按id属性相等的归结到resultList中
     * @param oneList
     * @param twoList
     */
    public static List<Map<Object, Object>> compareListHitData(List<Map<Object, Object>> oneList, List<Map<Object, Object>> twoList) {
          
   
        List<Map<Object, Object>> resultList = oneList.stream().map(map -> twoList.stream()
                .filter(m -> Objects.equals(m.get("id"), map.get("id")))
                .findFirst().map(m -> {
          
   
                    map.putAll(m);
                    return map;
                }).orElse(null))
                .filter(Objects::nonNull).collect(Collectors.toList());
        return resultList;
    }

2. Main方法测试

public static void main(String[] args) {
          
   
        List<Map<Object, Object>> oneList = new ArrayList<>();
        Map<Object, Object> oneMap = new HashMap<>();
        oneMap.put("id", 111);
        oneMap.put("userName", "何金荣");
        Map<Object, Object> twoMap = new HashMap<>();
        twoMap.put("id", 222);
        twoMap.put("userName", "Hejinrong");
        oneList.add(oneMap);
        oneList.add(twoMap);
        List<Map<Object, Object>> twoList = new ArrayList<>();
        Map<Object, Object> threeMap = new HashMap<>();
        threeMap.put("id", 111);
        threeMap.put("userName", "何金荣");
        Map<Object, Object> fourMap = new HashMap<>();
        fourMap.put("id", 333);
        fourMap.put("userName", "Hejinrong");
        twoList.add(threeMap);
        twoList.add(fourMap);
        List<Map<Object, Object>> resultList = compareListHitData(oneList, twoList);
        System.out.println(resultList);
    }

3. 输出结果

经验分享 程序员 微信小程序 职场和发展