繁体   English   中英

比较两个列表值并仅查找一个列表中不存在于另一个列表中的值

[英]Comparing two list values and finding only values from one list that do not exist in another

我有两个列表,如下所示

List<Test> fisrtList= Arrays.asList(
                new Test(1, 1L),
                new Test(2, 3L),
                new Test(2, 4L)
                
                );
        
List<Long> secondList=Arrays.asList(3L, 5L);
//Find value of second  list that are not in first list

比较的预期答案应该是 5L,因为它不在 firstList 中。

这是我的测试 class

public class Test {
    
    public Test(int id, Long idNo) {
        this.id=id;
        this.idNo=idNo;
    }

    private int id;
    
    private Long idNo;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Long getIdNo() {
        return idNo;
    }

    public void setIdNo(Long idNo) {
        this.idNo = idNo;
    }
    
}

如何从 secondList 中找到不在 firstList 中的 Long 值?

这会做到的

secondList.removeAll(firstList);

如果您需要不修改secondList ,则必须先制作深拷贝并使用深拷贝而不是secondList

如果您想为此目的使用流,最有效的方法如下所示:

    public static List<Long> removeIntersection(List<Long> source, List<Test> valuesToRemove) {
        Set<Long> toRemove = toSet(valuesToRemove);
        return source.stream()
                .filter(num -> !toRemove.contains(num))
                .collect(Collectors.toList());
    }
    private static Set<Long> toSet(List<Test> valuesToRemove) {
        return valuesToRemove.stream()
                .map(Test::getIdNo)
                .collect(Collectors.toSet());
    }

通过使用 Collection 接口中的removeAll()retainAll()方法可以实现相同的结果。 这些方法针对 ArrayList 进行了优化,并在线性时间内执行。

您只需要将您的测试对象列表转换为 Long 列表,并复制第二个列表,该列表将被变异。

为了演示这些方法如何工作,让我们考虑以下示例,其中包含 Integer 值列表。

removeAll()将从该集合中删除给定集合中包含的所有元素

retainAll()将只保留 collections 中包含的所有元素

    public static void main(String[] args) {
        List<Integer> source = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9));
        List<Integer> valuesToRemove = new ArrayList<>(List.of(1, 2, 3, 4));
        source.removeAll(valuesToRemove);
        System.out.println("result of removeAll: " + source);

        source = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9));
        List<Integer> valuesToRetain = new ArrayList<>(List.of(5, 6, 7, 8, 9));
        source.retainAll(valuesToRetain);
        System.out.println("result of retainAll: " + source);
    }

output

result of removeAll: [5, 6, 7, 8, 9]
result of retainAll: [5, 6, 7, 8, 9]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM