List difference in java

前端 未结 11 1782
野的像风
野的像风 2020-11-30 04:33

I have two ArrayList as follows:

original: 12, 16, 17, 19, 101

selected: 16, 19, 107, 108, 109

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:19

     List original;
     List selected;
    
     List add = new ArrayList(selected);
     add.removeAll(original);
    
     List remove = new ArrayList(original);
     remove.removeAll(selected);
    

    Be careful with border cases around duplicate elements. Should cardinality be respected? As in, if I had 5, 6 originally and 5, 5, 6 after, should add be 5? The above works better with Sets, since they don't have duplicates (plus contains() lookups are faster since they are indexed by the data they contain).

提交回复
热议问题