简体   繁体   English

我想从list1中删除list2元素并返回list1

[英]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.

相关问题 Java: list1=list2 // list1==list2? - Java: list1=list2 // list1==list2? 在不使用流的情况下过滤 list1 中不在 list2 java 中的元素 - Filter elements in list1 that are not in list2 java without using streams java项目list1到list2 - java items list1 to list2 将list1添加到list2并更新list1而不影响list2 - Adding list1 to list2 and updating list1 without affecting list2 Java 8 Streams:计算元素的出现次数(列表<String> list1) 来自文本数据列表(List<String> 清单 2) - Java 8 Streams : Count the occurrence of elements(List<String> list1) from list of text data(List<String> list2) 从 List1 中删除值也会从 List2 中删除值? - Removing values from List1 also removes values from List2? 更新list1中的参数 <object> 来自list2 <object> 通过使用java 8 - Update param in list1<object> from list2<object> by using java 8 确定 list2 是否包含 list1 的所有唯一 id 的对象以及这些对象是否还包含特定元素 - Determine whether list2 contains objects for all the unique ids of list1 and whether these objects also contain specific elements 如何合并清单 <Date> list1和List <Date> Java中的list2? - How to Union List<Date> list1 and List<Date> list2 in Java? 为什么我收到“列表的删除类型参数”错误 <String> list1 =新的ArrayList <String> ();” - Why i am getting “Remove type arguments” error for “List<String> list1 = new ArrayList<String>();”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM