package com.uama.utils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
/**
* 集合操作工具类
*
* @since 1.0
*/
public class CollectionUtil {
private CollectionUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 判断集合是否非空
*/
public static boolean isNotEmpty(Collection<?> collection) {
return CollectionUtils.isNotEmpty(collection);
}
/**
* 判断集合是否为空
*/
public static boolean isEmpty(Collection<?> collection) {
return CollectionUtils.isEmpty(collection);
}
/**
* 拷贝集合
*/
public static <T> List<T> deepCopy(List<T> src) {
if (src == null) {
return null;
}
return src.stream().collect(Collectors.toList());
}
/**
* 获取交集
* 交集的获取方法:
* 例:
* 集合A:{1,2,3}
* 集合B:{3,4}
* 先获取集合A和集合B的差集C:{1,2}
* 再获取集合A和差集C的差集D:{3},差集D就是交集
* Added By Fangxm 2017.06.06
* @param from 集合A
* @param src 集合B
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
public static <T> List<T> intersection(final List<T> a, final List<T> b) {
if (a == null || a.isEmpty()) {
return null;
}
if (b == null || b.isEmpty()) {
return null;
}
ArrayList<T> list = new ArrayList<>();
Map<T, Integer> mapa = getCardinalityMap(a);
Map<T, Integer> mapb = getCardinalityMap(b);
Set<T> elts = new HashSet<>(a);
elts.addAll(b); // addAll时会自动去重
Iterator<T> it = elts.iterator();
while (it.hasNext()) {
T obj = it.next();
// 由于去过重了, list要add的次数是两者的较小值
for (int i = 0, m = Math.min(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) {
list.add(obj);
}
}
return list;
}
/**
* 返回拥有相同obj的数量
* @param coll
* @return
*/
public static <T> Map<T, Integer> getCardinalityMap(final List<T> coll) {
Map<T, Integer> count = new HashMap<>();
for (Iterator<T> it = coll.iterator(); it.hasNext();) {
T obj = it.next();
Integer c = count.get(obj);
if (c == null) {
count.put(obj, 1);
} else {
count.put(obj, c.intValue() + 1);
}
}
return count;
}
/**
* 获取差集
* 例:
* 集合A:{1,2,3}
* 集合B:{3,4}
* 集合A和集合B的差集C:{1,2}
* Added By Fangxm 2017.06.06
*/
public static <T> List<T> differenceSet(List<T> from, List<T> src) {
if (src == null || src.isEmpty()) {
return from;
}
if (from == null || from.isEmpty()) {
return from;
}
List<T> dest = deepCopy(from);
return removeAll(dest, src);
}
}