Java8 - 比较2对象列表并形成具有旧值和新值的Map列表 [英] Java8 - Compare 2 List of objects and form a List of Map with old and new values
问题描述
比较两个对象列表并创建一个列表< Map< String,obj>
其中每个Map的键为old,其值为oldObj,键为newwith值为newObj
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
例如:第一个对象列表是 - > 列表< Company>
(更新列表)
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;
}
,第二个列表是 List< Company>
(旧值)
and second list is List<Company>
(old Values)
如何比较两个列表并形成列表< Map< string,Company>
其中每个Map的键值为old,值为oldObj,键值为new,值为newObj,其中要检查比较的字段是区域,代码,类型。
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.
例如:
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"))
谢谢。
推荐答案
您需要按步骤进行:
- 遍历
oldList
中的所有Company
(也可以通过交换旧列表和新列表来完成) - 找到与当前旧版相关的新
公司
:匹配代码/类型/区域
-
- 如果相关公司存在:将它们全部添加到新地图中
old和new
作为键,然后在listMap中添加
map
- 如果没有关联公司,请转到
- 如果相关公司存在:将它们全部添加到新地图中
- iterate over all
Company
in theoldList
(can be done also by swapping old and new lists) - find the new
Company
related to the current old one : matchcode/type/region
- If the related company exists : add them all in a new map with
"old" and "new"
as keys, then add thismap
in thelistMap
- If no related company, go next
- If the related company exists : add them all in a new map with
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);
});
}
这篇关于Java8 - 比较2对象列表并形成具有旧值和新值的Map列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!