[英]How to create a list of matching objects from multiple lists and delete objects in the matching list such that it reflects in the original list
[英]Aggregate List from equal objects in multiple Lists
我試圖創建一個List<Object> aggregated
基於List<Object> pool1
和List<Object> pool2
。 這里主要關注的是明顯的性能,因為我們要在每一個對象進行比較pool1
在每個對象pool2
。 List
是否是最佳選擇?
上面的錯誤代碼版本:
List<Object> pool1 = new ArrayList<>();
List<Object> pool2 = new ArrayList<>();
List<Object> matchingObjects = new ArrayList<Object>();
for (Object p1 : pool1) {
for (Object p2 : pool2) {
if (p1.equals(p2)) {
matchingObjects.add(p1);
}
}
}
retainAll
將在兩個列表之間提供一個common
元素
pool1.retainAll(pool2);
//pool1 contains elements common between two lists
如果您想要一個合理的常用元素列表,請按照以下過程進行操作
List<Object> matchingObjects = (ArrayList<Object>)pool1.clone();
matchingObjects.retainAll(pool2); // now matchingObjects will contain all the common elements
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.