首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较两个不同列表中的两个对象与同一对象列表中的两个对象

比较两个不同列表中的两个对象与同一对象列表中的两个对象
EN

Stack Overflow用户
提问于 2022-11-18 22:39:34
回答 1查看 31关注 0票数 -1

我有一个DTO对象列表

代码语言:javascript
复制
List<DTO> listOfObjects = new ArrayList<DTO>();

DTO有以下几个领域:

代码语言:javascript
复制
Class DTO {

private Integer id;
private List<Long> listOfNumbers = new ArrayList<Long>()

// Getters and Setters
}

我想比较一下listOfObjects中的子数组。

我正在使用Java 8,我的listOfObjects中有很多对象,如下所示:

代码语言:javascript
复制
listOfObjects => [{1,{1,2,3,4}}, {2, {3,4,5,6}}, {3, {5,6,7,8}} , {4, {4,14,28}}]

现在,我想通过iterate通过listOfObjects搜索哪些数组中有公共元素。在此之后,我希望从旧数组中删除重复数字(使用较小的id)。产出应是:

代码语言:javascript
复制
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

问题

我希望迭代一个List of ArrayList,并比较每个ArrayList,并删除与之比较的索引小于ArraylistArrayList中的重复项。我试过以下几点:

代码语言:javascript
复制
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。在我的尝试中,多次循环列表会导致一个大的Time Complexity

EN

回答 1

Stack Overflow用户

发布于 2022-11-19 00:49:02

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74496006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档