Intersection of two lists by object property

Spacejockey :

If I have two lists of objects, I can find the intersection as follows:

public class MyObject {
     String id;
     String someField;
     String someOtherField;
}

List<MyObject> list1;
List<MyObject> list2;

List<MyObject> intersect = list1.stream()
                           .filter(list2::contains)
                           .collect(Collectors.toList());

Is there a similar way to find the intersection based on the id field of MyObject? I can't override the equals method.

Nicko :

Similarly to Eran's answer above but perhaps with slightly more efficiency you could pull the IDs out into a separate Set first:

Set<String> ids = list2.stream().map(obj -> obj.id).collect(Collectors.toSet());

List<MyObject> intersect = list1.stream()
    .filter(obj -> ids.contains(obj.id))
    .collect(Collectors.toList());

The reason this would be more efficient is that for each item in list1 you can determine if the ID is in list2 in O(1) time so overally your runtime is O(list1 + list2)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127102&siteId=1