Java8 - Compare 2 List of objects and form a List

2019-09-21 20:08发布

Compare two list of objects and create a List<Map<String, obj> where each Map has key "old" with value as oldObj and key "new" with value as newObj

Eg: First List of Objects is -> List<Company> (Updated list)

class Company{
   String region;
   String code;
   String type;
   String contactPerson;
   String startDate;
   String endDate;
   String field1;
   String field2;
}

and second list is List<Company> (old Values)

How to compare both the lists and form a List<Map<string, Company> where each Map has key "old" with value as oldObj and key "new" with value as newObj where the fields to check for comparison are region, code, type.

eg:

List<Company> companyList = Arrays.asList( new Company("1", "100", "tier1", "bob", "2010", "20201"),  new Company("1", "101", "tier1", "rick", "2010", "20201"),  new Company("1", "101", "tier2", "personA", "2010", "20201"), new Company("2", "200", "tier3", "personC", "2010", "20201"))

List<Company> dbValues = Arrays.asList( new Company("1", "100", "tier1", "jenny", "2010", "20201"),  new Company("1", "101", "tier1", "rinson", "2010", "20201"),  new Company("1", "101", "tier2", "personB", "2018", "2020"), new Company("2", "200", "tier3", "personD", "2010", "20201"))

Thanks.

标签: java java-8
1条回答
Ridiculous、
2楼-- · 2019-09-21 20:28

You need to do it by steps :

  1. iterate over all Company in the oldList (can be done also by swapping old and new lists)
  2. find the new Company related to the current old one : match code/type/region
    • If the related company exists : add them all in a new map with "old" and "new" as keys, then add this map in the listMap
    • If no related company, go next

List<Company> oldList = // ;
List<Company> newList = // ;
List<Map<String, Company>> listMap = new ArrayList<>();

for (Company oldComp : oldList) {
    newList.stream()
           .filter(c -> c.code.equals(oldComp.code) &&
                   c.region.equals(oldComp.region) &&
                   c.type.equals(oldComp.type))
           .findAny()
           .ifPresent(newCorrespond -> {
                Map<String, Company> map = new HashMap<>();
                map.put("old", oldComp);
                map.put("new", newCorrespond);
                listMap.add(map);
           });
}
查看更多
登录 后发表回答