0

Is there a way to return the missing map of String from two list of map of string. My data is like this:

    List<Map<String,String>> customerDetails = new ArrayList<>();
    List<Map<String,String>> accountDetails = new ArrayList<>();

    Map<String,String> customerMap = new HashMap<String, String>() 
    {{put("id","1");put("name","Andy");put("Account","1050");}};
    customerDetails.add(customerMap);
    customerMap = new HashMap<String, String>() 
    {{put("id","2");put("name","Tom");put("Account","1049");}};
    customerDetails.add(customerMap);
    customerMap = new HashMap<String, String>() 
    {{put("id","3");put("name","Mary");put("Account","1052");}};
    customerDetails.add(customerMap);


    Map<String,String> accountMap = new HashMap<String, String>() 
    {{put("id","2");put("name","Tom");put("Account","1049");}};
    accountDetails.add(accountMap);
    accountMap = new HashMap<String, String>() 
    {{put("id","3");put("name","Mary");put("Account","1052");}};
    accountDetails.add(accountMap);

   

How can I combine these two list of maps avoiding duplicates?

halfer
  • 19,824
  • 17
  • 99
  • 186
nithinc
  • 11
  • 3
  • 7
    Why are you using maps in the first place? Create a `Person` class with 3 fields - `id`, `name` and `account`. – Sweeper Aug 17 '22 at 09:55
  • [Don’t use double-brace initialization of Maps.](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) But really, it’s moot, because Sweeper’s advice is very good advice. – VGR Aug 17 '22 at 12:27

3 Answers3

2

If both of your lists can contain unique items you could merge them together into a Set<> to remove duplicates. Then create a List<> again for your desired output:

Set<Map<String,String>> set = new HashSet<>();
set.addAll(customerDetails);
set.addAll(accountDetails);

List<Map<String,String>> combined = new ArrayList<>(set);

System.out.println(combined);

Output:

[{Account=1049, name=Tom, id=2}, {Account=1052, name=Mary, id=3}, {Account=1050, name=Andy, id=1}]
JANO
  • 2,995
  • 2
  • 14
  • 29
0

There are two lists of some objects, so basically one can remove the elements of one list from the other:

List<Map<String, String>> missing = new ArrayList<>(customerDetails);
missing.removeAll(accountDetails);
System.out.println("accountDetails missing " + missing);

But, as @Sweeper already stated, it's better to create a type for your data like e. g. Person.

Mihe
  • 2,270
  • 2
  • 4
  • 14
0

Java 8 version

List<Map<String, String>> combined =
        Stream.concat(customerDetails.stream(), accountDetails.stream())
                .distinct()
                .collect(Collectors.toList());

Please declare & use class (for example Person) instead of Map. Code became much more readable and error tolerant.

Bohdan Petrenko
  • 997
  • 2
  • 17
  • 34