I have two arrayLists and I am trying to \"subtract\" one arrayList from another. For example, if I have one arrayList [1,2,3] and I am trying to subtract [0, 2, 4] the resu
You can also use streams:
List list1 = Arrays.asList(1, 2, 3);
List list2 = Arrays.asList(1, 2, 4, 5);
List diff = list1.stream()
.filter(e -> !list2.contains(e))
.collect (Collectors.toList()); // (3)
This answer does not manipulate the original list. If intention is to modify the original list then we can use remove
. Also we can use forEach
(default method in Iterator
) or stream with filter.
Another option is to use ListUtils
if we are using Apache common:
ListUtils.subtract(list, list2)
This subtracts all elements in the second list from the first list, placing the results in a new list. This differs from List.removeAll(Collection)
in that cardinality is respected; if list1 contains two occurrences of null
and list2 only contains one occurrence, then the returned list will still contain one occurrence.