-1

I have list of hashmap and I want to join value if key is same below I have mentioned input and expected output .I have gone through many question answer related to this problem still couldn't found solution.

INPUT :

[
  {
    "id": "316",
    "text1": true
  },
  {
    "id": "316",
    "text2": true
  },
  {
    "id": "315",
    "text1": true
  },
  {
    "id": "315",
    "text2": true
  }
]

OUTPUT:

[
  {
    "id": "316",
    "text1": true,
    "text2": true
  },
  {
    "id": "315",
    "text1": true,
    "text2": true
  }
]

Code Snippet :

                    List list1= new ArrayList();
                    HashMap details= new HashMap();        
                    details.put("id", "305");
                    details.put("text1",true);    
                    list1.add(details); 
                    HashMap details2= new HashMap();
                    details2.put("id", "305");
                    details2.put("text2",true);              
        
                    list1.add(details2);       
        
Tejal
  • 764
  • 1
  • 10
  • 39
  • 3
    What have you tried so far? Have a look at `LinkedHashMap` is you need to keep the order, otherwise use a `Map>`, iterate over the list, put maps into the outer map by id and use `Map` methods like `merge()`. – Thomas Sep 08 '21 at 07:55
  • I tried few solution from stackoverflow .https://stackoverflow.com/questions/4299728/how-can-i-combine-two-hashmap-objects-containing-the-same-types/4299742 https://stackoverflow.com/questions/17607850/how-merge-list-when-combine-two-hashmap-objects-in-java?noredirect=1&lq=1 – Tejal Sep 08 '21 at 08:01
  • HashSet keys=new HashSet(); keys.add("316"); keys.add("315"); keys.forEach(id-> { list1.forEach(val -> { if (((LinkedHashMap) (val)).get("id").equals((String.valueOf(id)))) { programList.add(val); } }); }); this is sample code snippet which i tried – Tejal Sep 08 '21 at 08:02
  • 2
    Please reread my first comment: don't try to _cast_ the maps to `LinkedHashMap` but use it to store the merged maps. – Thomas Sep 08 '21 at 08:47
  • 2
    Stop using raw types. Include the necessary declarations, e.g. of `list1` and `list2`, in the question. JSON-dumps are not helpful for Java question. – Holger Sep 08 '21 at 08:51

1 Answers1

1

Based on @Thomas comment you can do like this:

Map<String, Map<String, Object>> mapMap = new HashMap<>();
    list.forEach(map -> map.entrySet().forEach(entry ->
            mapMap.merge((String) map.get("id"), map, (map1, map2) -> {
                map1.putAll(map2);
                return map1;
            }))
    );

System.out.println(mapMap.values());
Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • it worked . instead of merging into new map I was trying to merge into existing one only . any ways thanks for your great help . – Tejal Sep 08 '21 at 11:39