Skip to content
Advertisement

How to i compare two lists of different types in Java?

I have two lists:

The first list is a list of MyObject which contains an int and a String:

List<MyObject> myObjList = new ArrayList<>();

myObjList.add(new MyObject(1, "Frank"));
myObjList.add(new MyObject(2, "Bob"));
myObjList.add(new MyObject(3, "Nick"));
myObjList.add(new MyObject(4, "Brian"));

The second list is simply a list of strings:

List<String> personList = new ArrayList<>();
    
personList.add("Nick");

I want to compare the list of strings (personList) with string in the list of MyObject (myObjectList) and return a list of id’s with all the matches. So in the examle it should return a list containing only Nicks id -> 3. How do I do that?

UPDATE:

To get a list of id’s I simply said:

myObjectList.stream()
.filter(mo -> personList.contains(mo.id))
.map(MyObject::id)
.collect(Collectors.toList());

Advertisement

Answer

I’m not entirely clear which way round you want, but if you want the elements in personList which are ids of elements in myObjList:

personList.stream()
    .filter(s -> myObjList.stream().anyMatch(mo -> mo.id.equals(s)))
    .collect(Collectors.toList());

or, if you want the elements in myObjList whose ids are in personList:

myObjectList.stream()
    .filter(mo -> personList.contains(mo.id))
    .collect(Collectors.toList());

(In the latter case, it may be better for personList to be a Set<String>).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement