Subtracting one arrayList from another arrayList

后端 未结 9 933
无人及你
无人及你 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:41

    Try this answer if removeAll() is not what you want. e.g. if you are interested in something like Calculating difference of two lists with duplicates

    subtract(a,b)

    b.forEach((i)->a.remove(i));
    

    a now contains

    [1, 3]
    

    This follows the suggestion of Guava implementors on how to implement subtract

    "create an ArrayList containing a and then call remove on it for each element in b."

    Which behaves like this implementation used in Apache commons

    Difference to removeAll()

    [1,2,2,3].removeAll([1,2,3]) //is empty
    [1,2,3].forEach((i)->[1,2,2,3].remove(i)); //a is [2] 
    

提交回复
热议问题