java8写一个当List<B>中多个字段与List<A>进行match,match不到时,将只在List<B>中存在的数据出力的共通方法
时间: 2024-05-05 20:17:31 浏览: 154
可以使用Java 8的Stream API来实现这个功能。具体实现步骤如下:
1. 定义一个方法,参数为List<A>和List<B>,返回值为List<B>,表示只在List<B>中存在的数据。
2. 使用Stream的filter方法和anyMatch方法,对每个B对象进行判断,如果B对象的多个字段与List<A>中任意一个A对象的多个字段匹配,则将该B对象过滤掉。
3. 最后使用Stream的collect方法,将剩余的B对象收集到一个新的List中并返回。
下面是代码实现:
```java
public static <A, B> List<B> filterByMatch(List<A> listA, List<B> listB,
Function<B, List<Object>> bFieldsGetter,
Function<A, List<Object>> aFieldsGetter) {
return listB.stream()
.filter(b -> !listA.stream()
.anyMatch(a -> bFieldsGetter.apply(b).equals(aFieldsGetter.apply(a))))
.collect(Collectors.toList());
}
```
其中,bFieldsGetter和aFieldsGetter分别是获取B对象和A对象多个字段值的函数。使用时需要根据具体情况实现这两个函数。
示例代码:
```java
class A {
private int id;
private String name;
public A(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
class B {
private int id;
private String name;
private int age;
public B(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
List<A> listA = Arrays.asList(new A(1, "Alice"), new A(2, "Bob"));
List<B> listB = Arrays.asList(new B(1, "Alice", 20), new B(2, "Bob", 30),
new B(3, "Charlie", 25), new B(4, "David", 40));
List<B> result = filterByMatch(listA, listB,
b -> Arrays.asList(b.getId(), b.getName()),
a -> Arrays.asList(a.getId(), a.getName()));
System.out.println(result); // [B{id=3, name='Charlie', age=25}, B{id=4, name='David', age=40}]
}
}
```
在上面的示例中,我们通过调用filterByMatch方法,将只在List<B>中存在的数据筛选出来,并输出到控制台。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)