[英]The difference between the different methods to remove all same items from a list
[英]Difference between List items
我有两个列表ListOne和ListTwo。 我必须找出ListTwo中不存在的ListOne的所有元素。 同样,我必须找出ListOne中不存在的ListTwo的所有元素。
我下面的代码正在工作,但我认为可能会有更好的方法
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);
}
}
下面应该为您工作
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);
从Java文档中:
RemoveAll:从此列表中删除指定集合中包含的所有其元素(可选操作)。
作为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());
要真正提高效率,您可以执行以下操作:
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());
这样,您可以避免列表长度为m
和n
m*n
复杂性问题。
编辑:如果您更喜欢没有中介变量(如@davidxxx提到的),则可以这样做:
List<Long> listThree = listOne.stream()
.filter(not(new HashSet(listTwo)::contains))
.collect(Collectors.toList());
有多种否定谓词的方法。 已经回答了 ,这里不需要覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.