Collection comparison
From DarkWiki
Introduction
Code
package org.darkmine.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class CollectionsComparisonUtils {
/**
* The result of a comparison.
*
* @param <T>
*/
public static class Result<T> {
private Collection<T> added;
private Collection<T> removed;
private Result(Collection<T> added, Collection<T> removed) {
this.added = added;
this.removed = removed;
}
/**
* The items added to the collection.
*
* @return
*/
public Collection<T> getAdded() {
return added;
}
/**
* The items removed from the collection.
*
* @return
*/
public Collection<T> getRemoved() {
return removed;
}
/**
* The collections are the same.
*
* @return
*/
public boolean isSame() {
return added.size() + removed.size() == 0;
}
}
/**
* Implement this interface to determine if a collection contains an element or not.
* @param <T>
*/
public interface CollectionFinder<T> {
boolean contains(Collection<T> collection,T element);
}
/**
* The STANDARD_FINDER simply uses the Collections.contains() method.
*/
private static final CollectionFinder STANDARD_FINDER = (collection, element) -> collection.contains( element );
/**
* Compare the contents of two collections (it does not matter about the order).
*
* @param older The older collection.
* @param newer The newer collection.
* @param <T>
* @return
*/
public static <T> Result<T> compareAnyOrder(Collection<T> older, Collection<T> newer) {
return compareAnyOrder(older,newer,(CollectionFinder<T>) STANDARD_FINDER);
}
/**
* Compare the contents of two collections (it does not matter about the order).
*
* @param older The older collection.
* @param newer The newer collection.
* @param finder The class used to determine if a collection contains an element.
* @param <T>
* @return
*/
public static <T> Result<T> compareAnyOrder(Collection<T> older, Collection<T> newer, CollectionFinder<T> finder) {
if( older == null && newer == null ) {
return new Result<>(Collections.emptyList(),Collections.emptyList());
} else if( older == null ) {
return new Result<>(newer,Collections.emptyList());
} else if( newer == null ) {
return new Result<>(Collections.emptyList(),older);
} else {
Collection<T> added = new ArrayList<>();
Collection<T> removed = new ArrayList<>();
for( T o : older ) {
if( ! finder.contains( newer , o ) ) {
removed.add( o );
}
}
for( T o : newer ) {
if( ! finder.contains( older , o ) ) {
added.add( o );
}
}
return new Result<>(added,removed);
}
}
}