我有一个DTO
对象列表
List<DTO> listOfObjects = new ArrayList<DTO>();
DTO具有以下字段:
Class DTO {
private Integer id;
private List<Long> listOfNumbers = new ArrayList<Long>()
// Getters and Setters
}
我想比较listOfObjects
中的子数组。
我正在使用Java 8
,并且我的listOfObjects
中的对象数为:
listOfObjects => [{1,{1,2,3,4}}, {2, {3,4,5,6}}, {3, {5,6,7,8}} , {4, {4,14,28}}]
现在,我想从iterate
到listOfObjects
中搜索哪些数组中有公共元素。然后,我想从旧数组(id较小)中删除重复的数字。输出应该是:
listOfObjects => [{1,{1,2}}, {2, {3}}, {3, {5,6,7,8}}, {4, {4,14,28}}]
// Since the very first sub-Array had repeating element 3 and 4 from the next array. Therefore, number 3 and 4 must be removed from only the first sub-array. Similarly, 4th sub-array has the number 4 in it so second sub-array should not have it
问题
我想遍历一个'ArrayList'的列表,并将每个'ArrayList'相互比较,并从索引号小于与其比较的'ArrayList'的'ArrayList'中删除重复项。我尝试了以下方法:
private List<ProductDTO> removeDuplicateProductIds(List<ArrayList<Long>>DuplicateProductIds, List<ProductDTO> validProducts) {
//Removing duplicate product ids from old subList and keeping product ids in the latest subList
AtomicInteger i = new AtomicInteger(0);
DuplicateProductIds.forEach(duplicateId -> {
if (i.get() == DuplicateProductIds.size() - 1) {
return;
}
AtomicInteger j = new AtomicInteger(i.incrementAndGet());
i.decrementAndGet();
DuplicateProductIds.forEach(innerDuplicateId -> {
if (j.get() == DuplicateProductIds.size() - 1) {
return;
}
DuplicateProductIds.get(i.get()).removeAll(new HashSet<>(DuplicateProductIds.get(j.get())));
j.incrementAndGet();
});
i.incrementAndGet();
});
// Replacing new Product ids with unique ids in validProductBadges
i.set(0);
DuplicateProductIds.forEach(duplicateId -> {
if (i.get() == DuplicateProductIds.size() - 1) {
return;
}
validProducts.get(i.get()).setProductIdWithBadge(DuplicateProductIds.get(i.get()));
i.incrementAndGet();
});
return validProducts;
}
但是我正在寻找一种更有效的方法,可能是使用Java 8
的特性,比如stream
。
1条答案
按热度按时间pcww981p1#
可以使用for循环,然后在for循环中使用if语句来检查它们是否匹配。如果匹配,则可以使用remove函数将它们从数组列表中删除。