简体   繁体   English

清单项目之间的差异

[英]Difference between List items

i have two lists ListOne and ListTwo. 我有两个列表ListOne和ListTwo。 I have to find out all the elements of ListOne which does not exist in ListTwo. 我必须找出ListTwo中不存在的ListOne的所有元素。 Similarly I have to find out all the elements of ListTwo which does not exist in ListOne . 同样,我必须找出ListOne中不存在的ListTwo的所有元素。

My below code is working , but i am thinking there might be some better way 我下面的代码正在工作,但我认为可能会有更好的方法

        List<Long> listOne=...Some valid values;
        List<Long> listTwo=...Some valid values;
        List<Long> listThree=new ArrayList<Long>();
        List<Long> listFour=new ArrayList<Long>();

    for (Long id: ListOne) {
        if(!listTwo.contains(id)){
            listThree.add(id);
        }
    }

    for (Long id: ListTwo) {
        if(!listOne.contains(id)){
            listFour.add(id);
        }
    }

Below should work for you 下面应该为您工作

List<Long> listOne =...Some valid values;
List<Long> listTwo =...Some valid values;

List<Long> listThree = new ArrayList<>(listOne);
List<Long> listFour = new ArrayList<>(listTwo);
listThree.removeAll(listTwo);
listFour.removeAll(listOne);

From the java doc: 从Java文档中:

RemoveAll: Removes from this list all of its elements that are contained in the specified collection (optional operation). RemoveAll:从此列表中删除指定集合中包含的所有其元素(可选操作)。

As alternative to Lino answer, you can also rewrite your code in a functional way : 作为Lino答案的替代方法,您还可以采用功能性方式重写代码:

List<Long> listOneButListTwoElements = listOne.stream()
        .filter(l-> !listTwo.contains(l))
        .collect(Collectors.toList());


List<Long> listTwoButListOneElements = listTwo.stream()
        .filter(l-> !listOne.contains(l))
        .collect(Collectors.toList());

To be really efficient, you could do something like that: 要真正提高效率,您可以执行以下操作:

Set<Long> setOne = new HashSet<>(listOne);
Set<Long> setTwo = new HashSet<>(listTwo);

List<Long> listThree = listOne.stream()
        .filter(e -> !setTwo.contains(e))
        .collect(Collectors.toList());
List<Long> listFour = listTwo.stream()
        .filter(e -> !setOne.contains(e))
        .collect(Collectors.toList());

This way you avoid the problem with m*n complexity for list lengths m and n . 这样,您可以避免列表长度为mn m*n复杂性问题。


Edit: If you prefer having no intermediary variables (as @davidxxx mentioned), you could do it like: 编辑:如果您更喜欢没有中介变量(如@davidxxx提到的),则可以这样做:

List<Long> listThree = listOne.stream()
        .filter(not(new HashSet(listTwo)::contains))
        .collect(Collectors.toList());

There are various ways to negate a predicate. 有多种否定谓词的方法。 No need to cover it here, it has been answered . 已经回答了 ,这里不需要覆盖它。

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

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