java 将来自2个不同列表的2个对象与同一对象列表中的2个对象进行比较

webghufk  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(132)

我有一个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}}]

现在,我想从iteratelistOfObjects中搜索哪些数组中有公共元素。然后,我想从旧数组(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

pcww981p

pcww981p1#

可以使用for循环,然后在for循环中使用if语句来检查它们是否匹配。如果匹配,则可以使用remove函数将它们从数组列表中删除。

相关问题