当list<B>中多个字段组成的List<object>的值在list<A>中能找到一致的数据时,将这些数据根据更新条件将对应的字段值做更新后输出到新的list<B>中,并不改变原来的list<B>的值。用java8写一段实现上述需求的共通方法
时间: 2024-05-02 12:21:53 浏览: 19
假设A类和B类分别如下所示:
```java
class A {
private String id;
private String name;
private int age;
// Getter and Setter
}
class B {
private String id;
private String name;
private double salary;
// Getter and Setter
}
```
则可以定义一个通用方法 `updateListB`,其实现如下:
```java
public static List<B> updateListB(List<B> listB, List<A> listA, Function<A, String> idGetter, BiConsumer<B, A> updater) {
Map<String, B> mapB = listB.stream().collect(Collectors.toMap(B::getId, Function.identity()));
for (A a : listA) {
B b = mapB.get(a.getId());
if (b != null) {
updater.accept(b, a);
}
}
return listB;
}
```
其中,`idGetter` 函数用于从 A 对象中获取 ID 字段的值,`updater` 函数用于根据 A 对象更新 B 对象的字段值。例如,对于题目中给出的需求,`idGetter` 函数应该返回 B 和 A 对象中的 ID 字段的值,而 `updater` 函数应该更新 B 对象的字段值,例如:
```java
updateListB(listB, listA, A::getId, (b, a) -> {
b.setName(a.getName());
b.setSalary(a.getAge() * 1000);
});
```
完整的示例代码如下:
```java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
class A {
private String id;
private String name;
private int age;
public A(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class B {
private String id;
private String name;
private double salary;
public B(String id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
public class Main {
public static void main(String[] args) {
List<B> listB = Arrays.asList(
new B("001", "Alice", 1000),
new B("002", "Bob", 2000),
new B("003", "Charlie", 3000)
);
List<A> listA = Arrays.asList(
new A("001", "Alice Li", 25),
new A("002", "Bob Wang", 30),
new A("004", "David Zhang", 35)
);
updateListB(listB, listA, A::getId, (b, a) -> {
b.setName(a.getName());
b.setSalary(a.getAge() * 1000);
});
System.out.println(listB);
}
public static List<B> updateListB(List<B> listB, List<A> listA, Function<A, String> idGetter, BiConsumer<B, A> updater) {
Map<String, B> mapB = listB.stream().collect(Collectors.toMap(B::getId, Function.identity()));
for (A a : listA) {
B b = mapB.get(a.getId());
if (b != null) {
updater.accept(b, a);
}
}
return listB;
}
}
```