Merge two maps with Java 8

后端 未结 5 730
北荒
北荒 2020-12-06 17:04

I have two maps like this:

map1 = new Map();
map2 = new Map();

MyObject {
   Integer mark1;
   Integer mark2         


        
5条回答
  •  时光说笑
    2020-12-06 17:12

    Case 1: Given a List of Maps. Then Join the maps according to the Key

        public class Test14 {
    
            public static void main(String[] args) {
    
                Map> m1 = new HashMap<>();
                Map> m2 = new HashMap<>();
                m1.put("a", List.of(1));
                m1.put("b", List.of(2, 3));
                m2.put("a", List.of(12, 115));
                m2.put("b", List.of(2, 5));
                m2.put("c", List.of(6));
    
                System.out.println("map1 => " + m1);
                System.out.println("map2 => " + m2);
    
                ArrayList>> maplist = new ArrayList>>();
                maplist.add(m1);
                //   map1 => {a=[1], b=[2, 3]}
                maplist.add(m2);
                //      map2 => {a=[12, 115], b=[2, 5], c=[6]}
    
                System.out.println("maplist => " + maplist);
             //    maplist => [{a=[1], b=[2, 3]}, {a=[12, 115], b=[2, 5], c=[6]}]
    
    
                //  flatmap does omitted {} 
                List>> collect11 = 
                        maplist
                        .stream()
                        .flatMap(map -> map.entrySet().stream())
                        .collect(Collectors.toList());
                System.out.println(" collect11  => " + collect11);
                // collect11  => [a=[1], b=[2, 3], a=[12, 115], b=[2, 5], c=[6]]
    
                // That's why we will use this flatmap
    
    
                Map> map2 = maplist.stream()
                .flatMap(map -> map.entrySet().stream())
    
                .collect(
                        Collectors.toMap(
                                //keyMapper 
                                Map.Entry::getKey,
    
    
                                //valueMapper
                                Map.Entry::getValue,
    
                                (list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream())
                                .collect(Collectors.toList())
    
    
                                )//tomap
    
                        );
    //{a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
    
                System.out.println("After joining the maps according the key  => " + map2);
                // After joining the maps according the key  => {a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
    
                /*
                 OUTPUT :
    
                 After joining the maps according the key  => {a=[1, 12, 115], b=[2, 3, 2, 5], c=[6]}
                 */
    
            }// main
    
        }
    

提交回复
热议问题