在Java中比较两个集合 [英] Comparing two Collections in Java
问题描述
我在Java类中有两个集合。第一个集合包含以前的数据,第二个包含来自上一个集合的更新数据。
我想比较两个集合,但我不确定最有效的实现方法。两个集合将包含相同数量的项目。
然后基于carType在每个集合中相同,我想执行carType方法。
任何帮助赞赏
难以帮助,因为你没有告诉我们 (等大小)集合。有些想法希望适合:
如果两个集合在同一顺序中包含相同的对象,请比较
Iterator targetIt = target.iterator();
for(Object obj:source)
if(!obj.equals(targetIt.next()))
//比较结果 - > false
如果两个集合在任何顺序中包含相同的对象,
for(Object obj:source)
if(target.contains(obj))
比较结果 - > false
查找已更改的其他集合中的元素 b
$ b
Iterator targetIt = target.iterator();
pre>
for(Object obj:source)
if(!obj.equals(targetIt.next())
//元素已更改
根据您的评论,此算法会执行此操作,它会收集所有已更新的汽车对于
equals()
的正确实现,算法依赖 code> Car typepublic List< Car> findUpdatedCars(Collection< Car> oldCars,Collection< Car> newCars)
List< Car> updatedCars = new ArrayList< Car>();
迭代器oldIt = oldCars.iterator();
(Car newCar:newCars) {
if(!newCar.equals(oldIt.next()){
updatedCars.add(newCar);
}
}
return updatedCars;
}
I have two Collections in a Java class.The first collection contains previous data, the second contains updated data from the previous collection.
I would like to compare the two collections but I'm not sure of the best way to implement this efficiently.Both collections will contain the same amount of items.
Based then on the carType being the same in each collection I want to execute the carType method.
Any help is appreciated
解决方案Difficult to help, because you didn't tell us how you like to compare the (equal-size) collections. Some ideas, hoping one will fit:
Compare both collections if they contain the same objects in the same order
Iterator targetIt = target.iterator(); for (Object obj:source) if (!obj.equals(targetIt.next())) // compare result -> false
Compare both collections if they contain the same objects in the any order
for (Object obj:source) if (target.contains(obj)) // compare result -> false
Find elements in other collection that has changed
Iterator targetIt = target.iterator(); for (Object obj:source) if (!obj.equals(targetIt.next()) // Element has changed
Based on your comment, this algorithm would do it. It collects all Cars that have been updated. If the method result is an empty list, both collections contain equal entries in the same order. The algorithm relies on a correct implementation of
equals()
on theCar
type!public List<Car> findUpdatedCars(Collection<Car> oldCars, Collection<Car> newCars) List<Car> updatedCars = new ArrayList<Car>(); Iterator oldIt = oldCars.iterator(); for (Car newCar:newCars) { if (!newCar.equals(oldIt.next()) { updatedCars.add(newCar); } } return updatedCars; }
这篇关于在Java中比较两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!