import java.util.*;

/**
* @author 赵超
*/
public class ListUtil {

private static final Integer INTEGER_ONE = 1;

/**
* 截取列表list
* @param list 待截取列表
* @param size 每段长度
* @param <T> 列表范型类型
* @return
*/
public static <T> List<List<T>> subList(List<T> list, int size) {
List<List<T>> res = new ArrayList<>();
int times = list.size() / size + (list.size() % size == 0 ? 0 : 1);
for (int i = 1; i <= times; i++) {
List<T> temp = list.subList(size * (i - 1), i == times ? list.size() : size * i);
res.add(temp);
}
return res;
}

/**
* 判断两个集合中的元素是否相同
* @param a
* @param b
* @return
*/
public static boolean isEqualCollection(Collection a, Collection b) {
if (a == null || b == null || a.size() != b.size()) { // size是最简单的相等条件
return false;
}
Map mapa = getCardinalityMap(a);
Map mapb = getCardinalityMap(b);

// 转换map后,能去掉重复的,这时候size就是非重复项,也是先决条件
if (mapa.size() != mapb.size()) {
return false;
}
Iterator it = mapa.keySet().iterator();
while (it.hasNext()) {
Object obj = it.next();
// 查询同一个obj,首先两边都要有,而且还要校验重复个数,就是map.value
if (getFreq(obj, mapa) != getFreq(obj, mapb)) {
return false;
}
}
return true;
}

/**
* 以obj为key,可以防止重复,如果重复就value++
* 这样实际上记录了元素以及出现的次数
*/
public static Map getCardinalityMap(Collection coll) {
Map count = new HashMap();
for (Iterator it = coll.iterator(); it.hasNext(); ) {
Object obj = it.next();
Integer c = (Integer) count.get(obj);
if (c == null)
count.put(obj, INTEGER_ONE);
else {
count.put(obj, c.intValue() + 1);
}
}
return count;
}

private static final int getFreq(Object obj, Map freqMap) {
Integer count = (Integer) freqMap.get(obj);
if (count != null) {
return count.intValue();
}
return 0;
}
}