1 import java.util.ArrayList;
2 import java.util.Arrays;
3 import java.util.Collection;
4
5 import org.apache.commons.collections.CollectionUtils;
6
7 public class CollectionModificationHelper<T> {
8 private Collection<T> oldCollection;
9 private Collection<T> newCollection;
10
11 private Collection<T> newElements = new ArrayList<T>();
12 private Collection<T> commonElements = new ArrayList<T>();
13 private Collection<T> removedElements = new ArrayList<T>();
14
15 public CollectionModificationHelper(Collection<T> oldCollection,
16 Collection<T> newCollection) {
17 super();
18 this.oldCollection = oldCollection;
19 this.newCollection = newCollection;
20
21 init();
22 }
23
24 public CollectionModificationHelper(T[] oldArray, T[] newArray) {
25 this((oldArray == null ? null : Arrays.asList(oldArray)), (newArray == null ? null : Arrays.asList(newArray)));
26 }
27
28 private void init() {
29 if(CollectionUtils.isEmpty(oldCollection) && CollectionUtils.isEmpty(newCollection)) {
30 //nothing to do!
31 } else if(CollectionUtils.isEmpty(oldCollection)) {
32 if(!CollectionUtils.isEmpty(newCollection)) {
33 this.newElements = new ArrayList<T>(newCollection);
34 }
35 } else if(CollectionUtils.isEmpty(newCollection)) {
36 if(!CollectionUtils.isEmpty(oldCollection)) {
37 this.removedElements = new ArrayList<T>(oldCollection);
38 }
39 } else {
40 for(T item : oldCollection) {
41 if(newCollection.contains(item)) {
42 commonElements.add(item);
43 } else {
44 removedElements.add(item);
45 }
46 }
47
48 newElements.addAll(newCollection); //first add all new Collection in new element.
49 newElements.removeAll(commonElements); //then remove the common elements.
50 }
51 }
52
53 public Collection<T> getCommonElements() {
54 return commonElements;
55 }
56
57 public Collection<T> getNewElements() {
58 return newElements;
59 }
60
61 public Collection<T> getRemovedElements() {
62 return removedElements;
63 }
64 }
65