java8合并两个List

解决问题:根据两个List中的某个相同字段合并成一条List,包含两个List中的字段
举例:
list1:
[{pid=1,pname=衣服,picture=http://1.jpg,desc=111},{pid=2,pname=衣服2,picture=http://2.jpg,desc=222}]
list2:
[{pid=1,sku=L,price=200.00,price2=189},{pid=2,sku=s,price=100.00,price2=340}]
合并之后结果为:
[{price=200.00, pname=衣服, pid=1, sku=L, picture=http://1.jpg, price2=189, desc=111}, {price=100.00, pname=衣服2, pid=2, sku=s, picture=http://2.jpg, price2=340, desc=222}]

代码实现:

public class Test7 { 

    public static void main(String[] args) { 

        List<Map<String,Object>> list1 = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("pid",1);
        map1.put("pname","衣服");
        map1.put("picture","http://1.jpg");
        map1.put("desc","111");
        Map<String,Object> map2 = new HashMap<>();
        map2.put("pid",2);
        map2.put("pname","衣服2");
        map2.put("picture","http://2.jpg");
        map2.put("desc","222");
        list1.add(map1);
        list1.add(map2);
        List<Map<String,Object>> list2 = new ArrayList<>();
        Map<String,Object> map3 = new HashMap<>();
        map3.put("pid",1);
        map3.put("sku","L");
        map3.put("price","200.00");
        map3.put("price2","189");
        Map<String,Object> map4 = new HashMap<>();
        map4.put("pid",2);
        map4.put("sku","s");
        map4.put("price","100.00");
        map4.put("price2","340");
        list2.add(map3);
        list2.add(map4);
        List<Map<String,Object>> resultList = mergeList(list1,list2,"pid");
        System.out.println(resultList);
    }

    public static List<Map<String,Object>> mergeList(List<Map<String,Object>>list1, List<Map<String,Object>> list2, String filedName) { 
        List<Map<String, Object>> reaultList = new ArrayList<>();
        list1.stream().forEach(item1 -> { 
            Map<String, Object> map1 = list2.stream().filter(item2 -> item2.get(filedName).equals(item1.get(filedName))).findFirst().get();

            List<Map<String, Object>> newlist = new ArrayList();

            newlist.add(item1);
            newlist.add(map1);

            Map<String, Object> map2 = newlist.stream().map(Map::entrySet)
                    .flatMap(Set::stream)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(v1, v2) -> v1));
            reaultList.add(map2);
        });
        return reaultList;
    }
}
    原文作者:粉蒸妹
    原文地址: https://blog.csdn.net/Opal_123/article/details/106519056
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞