Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading