简体   繁体   中英

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());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM