I have two ArrayList
as follows:
original: 12, 16, 17, 19, 101
selected: 16, 19, 107, 108, 109
List<Integer> original = Arrays.asList(12,16,17,19,101);
List<Integer> selected = Arrays.asList(16,19,107,108,109);
ArrayList<Integer> add = new ArrayList<Integer>(selected);
add.removeAll(original);
System.out.println("Add: " + add);
ArrayList<Integer> remove = new ArrayList<Integer>(original);
remove.removeAll(selected);
System.out.println("Remove: " + remove);
Output:
Add: [107, 108, 109]
Remove: [12, 17, 101]
Uses Collection's removeAll method. See javadocs.
As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.
Use this method if you want to get intersection of a list of lists
List<Address> resultsIntersectionSet( List<Set<Address>> inputListOfLists )
{
Set<Address> intersection = new HashSet<>();
if ( !inputListOfLists.isEmpty() )
intersection = inputListOfLists.get( 0 );
for ( Set<Address> filterResultList : inputListOfLists )
{
intersection.retainAll( filterResultList );
}
return new ArrayList<>( intersection );
}
List<Integer> original;
List<Integer> selected;
List<Integer> add = new ArrayList<Integer>(selected);
add.removeAll(original);
List<Integer> remove = new ArrayList<Integer>(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 Set
s, since they don't have duplicates (plus contains()
lookups are faster since they are indexed by the data they contain).
For intersection and union operations the natural collection type is a Set rather than a List, its also more efficient to use.