3 回答

TA貢獻1804條經驗 獲得超2個贊
您可以使用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());
這假設兩者的組合name并且在 ingcity時匹配filter。

TA貢獻1826條經驗 獲得超6個贊
您需要override equals在類中使用方法App2:
public class App2{
private String differentName;
private String differentCity;
private String someProperty1;
private String someProperty2;
// getter setter
// constructors
@Override
public boolean equals(Object obj) {
App2 app2 = (App2) obj;
return this.differentName.equals(app2.getDifferentName()) && this.differentCity.equals(app2.getDifferentCity());
}
}
然后您可以像這樣在 list1 上使用 Streams:
app1List = app1List.stream()
.filter(a-> !app2List.contains(new App2(a.getName(),a.getCity())))
.collect(Collectors.toList());
輸出:
[App1{name='test1', city='city1'}, App1{name='test4', city='city4'}]

TA貢獻1829條經驗 獲得超7個贊
假設您想要匹配名稱和城市,您可以創建一個將對象映射到key的函數,例如:
public static Integer key(String name, String differentCity) {
return Objects.hash(name, differentCity);
}
然后使用該鍵創建一組鍵,以便使用noneMatch進行過濾,例如:
Set<Integer> sieve = app2List.stream()
.map(app2 -> key(app2.differentName, app2.differentCity)).collect(Collectors.toSet());
List<App1> result = app1List.stream().filter(app1 -> sieve.stream()
.noneMatch(i -> i.equals(key(app1.name, app1.city))))
.collect(Collectors.toList());
System.out.println(result);
輸出
[App1{name='test1', city='city1'}, App1{name='test4', city='city4'}]
這種方法的復雜性在于O(n + m)其中n和m是列表的長度。
添加回答
舉報