简体   繁体   中英

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. 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. I did it in java7 and it works fine but I want this in Java8. can anyone help me?

Method 1

You can use the removeAll method to remove the items of one list from another list.

To obtain the duplicates you can use the retainAll method, though your approach with the set is also good (and probably more efficient).

list1.removeAll(list2);

Method 2

You can use org.apache.commons.collections.ListUtils and make all that you want in only one line.

List resultList = ListUtils.subtract(list, list2);

Method 3

For Java 8 you can use Streams :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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