当List<B>以复数字段作为keyList与List<A>进行match,match成功时,将List<B>根据条件将部分字段更新后生成新的list,并且要求不改变原来List<B>的值。用Java8写一个满足需求的共通方法
时间: 2024-05-08 07:16:10 浏览: 10
假设有如下的类定义:
```
class A {
private int id;
private String name;
// getters and setters
}
class B {
private int id;
private String name;
private int count;
// getters and setters
}
```
则可以使用如下的Java8方法实现上述需求:
```
public static List<B> updateBList(List<B> bList, List<A> aList) {
Map<Integer, A> aMap = aList.stream().collect(Collectors.toMap(A::getId, Function.identity()));
return bList.stream()
.map(b -> aMap.containsKey(b.getId()) ? updateB(b, aMap.get(b.getId())) : b)
.collect(Collectors.toList());
}
private static B updateB(B b, A a) {
if (a.getName() != null) {
b.setName(a.getName());
}
if (a.getId() != b.getId()) {
b.setId(a.getId());
}
// update other fields as needed
return b;
}
```
这个方法接受两个参数:一个是List<B>,另一个是List<A>。它首先将List<A>转换为Map<Integer, A>,其中Integer是A的id字段,A是对应的对象。然后对于List<B>中的每个B对象,判断是否在Map中存在对应的A对象。如果存在,则调用updateB方法将B对象更新为新的值;否则不做修改。最终返回更新后的List<B>对象。注意,这个方法不会改变原始的List<B>对象,而是返回一个新的List。