两种方法:
1.集合相减可以使用阿帕奇的一个ListUtils.subtract(list1,list2)方法,这种方法实现必须重写集合中对象的属性的hashCode和equals方法,集合相减判断的会调用equals方法,
这种方法的好处是可以重写多个属性的hashCode和equals方法,也就是说用阿帕奇集合相减比较多个属性的比较灵活多样。带来的问题也比较明显,重写hashCode和equals方法后,
在使用hashMap时要特别注意。
2.自己实现一个集合相减的方法。用hashMap实现 这种方法不需要重写hashCode和equals方法,但是只能对一个属性进行比较相减。
/**
* 依据集合元素的属性,从list1中减去list2中存在的元素,
*
* @param list1
* @param list2
* @param argumentName
* @return
*/
public static <T> List<T> subtractList(List<T> list1, List<T> list2, String argumentName) {
List<T> result = new ArrayList<T>();
if (CollectionUtils.isEmpty(list1)) {
return result;
}
if (CollectionUtils.isEmpty(list2)) {
return list1;
}
Map<Object, T> map = initMap(list2, argumentName);
for (T t : list1) {
BeanWrapper beanWrapper = new BeanWrapperImpl(t);
Object value = beanWrapper.getPropertyValue(argumentName);
if (map.get(value) == null) {
result.add(t);
}
}
return result;
}
private static <T> Map<Object, T> initMap(List<T> list2, String argumentName) {
Map<Object, T> resultMap = new HashMap<Object, T>(list2.size());
for (T t : list2) {
BeanWrapper beanWrapper = new BeanWrapperImpl(t);
if (beanWrapper.getPropertyValue(argumentName) == null) {
throw new RuntimeException("argumentName is null");
}
resultMap.put(beanWrapper.getPropertyValue(argumentName), t);
}
return resultMap;
}
依据自己的业务需求,自行选择。