0

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?

4

2 回答 2

3

为什么不只迭代第二个列表?

for(ObjectVO objVO : list2){
    objVO.setFlag(list1.contains(objVO.getId()));
}
于 2013-03-21T20:30:47.607 回答
0

您可以将第二个列表转换为相同的数据类型,使其具有可比性,并使用 Apache Commons 集合来查找交集。只需将所有 ObjectVO.getId() 放入一个列表中。

Collection intersection = CollectionUtils.intersection(a, b);
于 2013-03-21T20:47:46.423 回答