Collection內的Class必須實作 hashCode 和 equal
因為原理是使用equal這個方法在比較
public class CompareCollectionUtil {
/**
* a = [1, 2, 3] b = [2, 3, 4]
* 比對兩個List 用 a 去跟 b 比較,回傳缺少的部分
* return [1]
**/
public static <T> List<T> deleted(Collection<T> a, Collection<T> b) {
if(a == null){
return new ArrayList<T>();
}
List<T> result = new ArrayList<T>(a);
if(b != null){
result.removeAll(b);
}
return result;
}
/**
* a = [1, 2, 3] b = [2, 3, 4]
* 比對兩個List 用 a 去跟 b 比較,回傳相同的部分
* return [2, 3]
**/
public static <T> List<T> retained(Collection<T> a, Collection<T> b) {
if(a == null || b == null){
return new ArrayList<T>();
}
List<T> result = new ArrayList<T>(a);
result.retainAll(b);
return result;
}
/**
* a = [1, 2, 3] b = [2, 3, 4]
* 比對兩個List 用 a 去跟 b 比較,回傳多的部分
* return [4]
**/
public static <T> List<T> added(Collection<T> a, Collection<T> b) {
return deleted(b, a);
}
/**
* a = [1, 2, 3] b = [2, 3, 4]
* 比對兩個List 用 a 去跟 b 比較,回傳不同的部分
* return [1, 4]
**/
public static <T> List<T> different(Collection<T> a, Collection<T> b){
List<T> list = new ArrayList<T>();
list.addAll(added(a, b));
list.addAll(deleted(a, b));
return list;
}
}
沒有留言:
張貼留言