Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists for updates, deletions and additions

Simple question.

I have a new list and an old list. In Java is there a standard way/library that allows me to compare these two lists and determine which items have been updated/deleted or are completely new? E.g. I should end up with three lists - Deleted items (items in old but not in new), Updated items (items in both), New items (items in new and not in old).

I could write this myself but was wondering if there is a standard way to do it.

The objects in the list implement equals correctly.

like image 811
Pablojim Avatar asked Nov 03 '09 13:11

Pablojim


1 Answers

No standard way sorry. You can do it fairly easily with the standard JDK without resorting to adding a dependency on Apache Commons (as others have suggested) however. Assuming your lists are List<T> instances:

List<T> oldList = ...
List<T> newList= ...

List<T> removed = new ArrayList<T>(oldList);
removed.removeAll(newList);

List<T> same = new ArrayList<T>(oldList);
same.retainAll(newList);

List<T> added = new ArrayList<T>(newList);
added.removeAll(oldList);
like image 92
cletus Avatar answered Oct 18 '22 09:10

cletus