我必须比较两个列表(list1 到 list2)上的元素,当元素与 code 属性的元素匹配时, 我必须替换为 tobereplace 属性的值。
在列表1中我有
[{code:"1", name:"first name", tobereplace: ""} , {code:"2", name:"first name1", tobereplace: ""},
{code:"3", name:"first name2", tobereplace: ""}, {code:"4", name:"first name3", tobereplace: ""}]
在List2中我有:
[{code:"1", name:"first name", tobereplace: ""} , {code:"2", name:"first name1", tobereplace: "" },
{code:"3", name:"first name2", tobereplace: ""}, {code:"4", name:"first name3", tobereplace: "this should come in list1"}]
理想情况下,List1 应该具有 List2 的值; 我们如何使用 Java8 流来实现这一点
最佳答案
假设该类名为 Foo
并且要更改的字段是带有 getter/setter 的 String valueToReplace
,您可以使用 listOne.replaceAll()
这样:
list1.replaceAll(one -> list2.stream()
.filter(other -> other.getCode().equals(one.getCode())
.findAny()
.map(Foo::getValueToReplace)
.ifPresent( newValue -> one.setValueToReplace(newValue));
return one;
)
这个想法是,对于 list1
的每个元素,将其 valueToReplace
字段替换为 list2
的第一个匹配项的值。否则你什么也不做。
这段代码的效率并不高,但对于小列表来说它是完美的。
对于更大的列表,使用 Map
来存储 code/valueToReplace
是非常受欢迎的。
// supposing that the code are unique in each list
Map<Integer, String> mapOfValueToReplaceByCode =
list2.stream()
.collect(toMap(Foo::getCode, Foo::getValueToReplace));
list1.replaceAll(one -> {
String newValue = mapOfValueToReplaceByCode.get(one.getCode());
if (newValue != null){
one.setValueToReplace(newValue);
}
return one;
)
关于java 8根据属性比较2个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710026/