Home > database >  How to compare two list of map and return the missing elements as a list?
How to compare two list of map and return the missing elements as a list?

Time:08-17

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? Please help.Thanks

CodePudding user response:

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}]

CodePudding user response:

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.

CodePudding user response:

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.

  • Related