Subtracting one arrayList from another arrayList

后端 未结 9 926
无人及你
无人及你 2021-01-01 11:00

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

9条回答
  •  粉色の甜心
    2021-01-01 11:59

    Java 8

    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.

    Using ListUtils

    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.

提交回复
热议问题