Please consider 2 Classes:
Class Object1 {
int id;
String test;
...
}
Class Object2 {
int id;
Boolean flag;
...
}
Object1 and Object2 are not equal.
Now, please consider I have a list of Object1 and Object2 as follows:
List<Object1>
Set<Object2>
Problem statement: I need to write a filter condition in the Java streams where
Object1.getId() == Object2.getId().
Can you please guide me here.
Edit: I want to filter List.
Do you want to compare elements pairwise or check for inclusion anywhere in the second collection? I want to check for inclusion anywhere in the second collection.
You can use Java 8 Lambda.
Object1 List and Object2 Set
List<Object1> object1List = ...
Set<Object2> object2Set = ...
Filter Object1
Map<Integer, Object2> object2Map = object2Set.stream()
.collect(Collectors.toMap(Object2::getId, Function.identity()));
List<Object1> result = object1List.stream()
.filter(a -> object2Map.containsKey(a.getId()))
.collect(Collectors.toList());