[英]I want remove list2 elements from list1 and return the list1
I have two Lists 我有两个清单
List<myObject> list1 = new ArrayList<>();
list1.add("544");
list1.add("545");
list1.add("546");
list1.add("547");
list1.add("548");
list1.add("549");
List<myObject> list2 = new ArrayList<>();
list2.add("547");
list2.add("548");
Now I want to remove list2 from list1 and return list1. 现在,我想从list1中删除list2并返回list1。 so my final returning list will look like
所以我的最终归还清单看起来像
List<myObject> list1 = new ArrayList<>();
list1.add("544");
list1.add("545");
list1.add("546");
list1.add("549");
I want to do this in Java8. 我想在Java8中做到这一点。 I did it in java7 and it works fine but I want this in Java8.
我在java7中做到了,它工作正常,但是我想要在Java8中做到这一点。 can anyone help me?
谁能帮我?
Method 1 方法1
You can use the removeAll
method to remove the items of one list from another list. 您可以使用
removeAll
方法从一个列表中删除另一个列表中的项目。
To obtain the duplicates you can use the retainAll
method, though your approach with the set is also good (and probably more efficient). 要获得重复项,可以使用
retainAll
方法,尽管使用集合的方法也很好(并且可能更有效)。
list1.removeAll(list2); list1.removeAll(list2);
Method 2 方法2
You can use org.apache.commons.collections.ListUtils and make all that you want in only one line. 您可以使用org.apache.commons.collections.ListUtils并在一行中完成所有所需的操作。
List resultList = ListUtils.subtract(list, list2);
Method 3 方法3
For Java 8 you can use Streams : 对于Java 8,您可以使用Streams:
List<Integer> diff = list1.stream()
.filter(i -> !list2.contains(i))
.collect (Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.