Amit :
I have 2 lists which are different from one another
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"));
As you see the App1 & App2 class are 2 different pojos having different property names, however the content/value that's held by name,city & differentName,differentCity property respectively is same i.e. test1, test2, test3 & city1, city2 etc
Now I need to filter app1List comparing names & city in other list i.e. app2List that doesn't exists.
final output would be
app1List.add(new App1("test1","city1"));
app1List.add(new App1("test4","city4"));
Easiest way is to loop one of the other lists multiple time which i am trying to avoid. Is there any way in Java 8 streams without having to loop multiple times??
Naman :
You can make use of noneMatch
operation, such as:
List<App1> result = app1List.stream()
.filter(app1 -> app2List.stream()
.noneMatch(app2 -> app2.getDifferentCity().equals(app1.getCity()) &&
app2.getDifferentName().equals(app1.getName())))
.collect(Collectors.toList());
This assumes the combination of both name
and city
is matched while filter
ing.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325432&siteId=1