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

时间:2021-12-26 16:13:27

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. so my final returning list will look like

现在我想从list1中删除list2并返回list1。所以我的最终回归清单看起来像

List<myObject> list1 = new ArrayList<>();
list1.add("544");
list1.add("545");
list1.add("546");
list1.add("549"); 

I want to do this in Java8. I did it in java7 and it works fine but I want this in Java8. can anyone help me?

我想在Java8中这样做。我在java7中做到了它并且工作正常,但我想在Java8中使用它。谁能帮我?

1 个解决方案

#1


3  

Method 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);

Method 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

For Java 8 you can use Streams :

对于Java 8,您可以使用Streams:

List<Integer> diff = list1.stream()
                          .filter(i -> !list2.contains(i))
                          .collect (Collectors.toList());

#1


3  

Method 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);

Method 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

For Java 8 you can use Streams :

对于Java 8,您可以使用Streams:

List<Integer> diff = list1.stream()
                          .filter(i -> !list2.contains(i))
                          .collect (Collectors.toList());