简体   繁体   中英

how to look for items in one list from another list in java

I have 2 lists, i'm iterating list1.. if the current item in list1 exists in list2 then i need to make a change in the property of list1.

The lists are just list of objects:

list1 = [ObjectVO, ObjectVO]
list2 = ['w', 'x', 'y', 'z']

where ObjectVO.getId() would return a string such as 'w', ...'z'

My code is as follows:

Iterator it = list1.iterator();
while(it.hasNext()){
    objVO = (ObjectVO) it.next();
    if(list2.contains(objVO.getId()){
        objVO.setFlag(true);  
    }
}

The problem here is that the the objVO.setFlag(true) is being executed always! like list2 contains all items in list 1 but that's not true, list 2 is only a subset of list1 so it shouldn't evaluate to true for all of them.

How do I fix this or is there a better way to accomplish this?

why not just iterate the second list?,

for(ObjectVO objVO : list2){
    objVO.setFlag(list1.contains(objVO.getId()));
}

You could convert the second list to the same datatype so it's comparable and the use Apache Commons collections to find the intersection. Just put all the ObjectVO.getId() into one list.

Collection intersection = CollectionUtils.intersection(a, b);

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