Subtracting one arrayList from another arrayList

后端 未结 9 879
无人及你
无人及你 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<Integer> list1 =  Arrays.asList(1, 2, 3);
    List<Integer> list2 =  Arrays.asList(1, 2, 4, 5);
    List<Integer> 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.

    0 讨论(0)
  • 2021-01-01 12:01

    Is there some reason you can't simply use List.removeAll(List)?

        List<Integer> one = new ArrayList<Integer>();
        one.add(1);
        one.add(2);
        one.add(3);
        List<Integer> two = new ArrayList<Integer>();
        two.add(0);
        two.add(2);
        two.add(4);
        one.removeAll(two);
        System.out.println(one);
    
        result: "[1, 3]"
    
    0 讨论(0)
  • 2021-01-01 12:01

    Try to use subtract method of org.apache.commons.collections.CollectionUtils class.

    Returns a new Collection containing a - b. The cardinality of each element e in the returned Collection will be the cardinality of e in a minus the cardinality of e in b, or zero, whichever is greater.

    CollectionUtils.subtract(java.util.Collection a, java.util.Collection b) 
    

    From Apache Commons Collections

    0 讨论(0)
提交回复
热议问题