gpt4 book ai didi

Java 8 流 - 通过比较两个列表进行过滤

转载 作者:行者123 更新时间:2023-11-29 04:06:43 25 4
gpt4 key购买 nike

我有两个不同的列表

public class App1{
private String name;
private String city;

// getter setter

// constructors
}

public class App2{
private String differentName;
private String differentCity;
private String someProperty1;
private String someProperty2;

// getter setter

// constructors
}

List<App1> app1List = new ArrayList<>();
app1List.add(new App1("test1","city1"));
app1List.add(new App1("test2","city2"));
app1List.add(new App1("test3","city3"));
app1List.add(new App1("test4","city4"));

List<App2> app2List = new ArrayList<>();
app2List.add(new App2("test2","city2"));
app2List.add(new App2("test3","city3"));

如您所见,App1 和 App2 类是 2 个具有不同属性名称的不同 pojo,但是 name、city 和 differentName、differentCity 属性分别持有的内容/值是相同的,即 test1、test2、test3 和 city1、city2 等

现在我需要过滤 app1List,比较其他列表中的名称和城市,即不存在的 app2List。

最终输出将是

app1List.add(new App1("test1","city1"));
app1List.add(new App1("test4","city4"));

最简单的方法是多次循环其他列表之一,我试图避免这种情况。在 Java 8 流中有什么方法可以不用多次循环吗??

最佳答案

可以利用noneMatch操作,如:

List<App1> result = app1List.stream()
.filter(app1 -> app2List.stream()
.noneMatch(app2 -> app2.getDifferentCity().equals(app1.getCity()) &&
app2.getDifferentName().equals(app1.getName())))
.collect(Collectors.toList());

这假设 namecity 的组合在 filtering 时匹配。

关于Java 8 流 - 通过比较两个列表进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58134699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com