public final class CollectionUtils {
private CollectionUtils() {
}
public static <T> boolean isNullOrEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
public static <T> boolean isNullOrEmpty(T[] array) {
return array == null || array.length == 0;
}
public static <K, V> boolean isNullOrEmpty(Map<K, V> map) {
return map == null || map.isEmpty();
}
public static <T> boolean contains(T[] array, T val) {
for (T t : array) {
if (val.equals(t)) {
return true;
}
}
return false;
}
public static <T> T head(List<T> list) {
return list.get(0);
}
public static <T> T end(List<T> list) {
return list.get(list.size() - 1);
}
public static <T, R> List<R> map(List<T> list, Function<? super T, R> function) {
return list.stream().map(function).collect(Collectors.toList());
}
public static <K, V> LinkedHashMap<K, V> ofMap(List<V> list, Function<V, K> keyFunction) {
LinkedHashMap<K, V> result = Maps.newLinkedHashMap();
for (V value : list) {
result.put(keyFunction.apply(value), value);
}
return result;
}
public static <K, V> ListMultimap<K, V> groupBy(List<V> list, Function<V, K> keyFunction) {
ListMultimap<K, V> result = ArrayListMultimap.create();
for (V value : list) {
result.put(keyFunction.apply(value), value);
}
return result;
}
/**
* 分割List
*
* @param list
* 待分割的list
* @param pageSize
* 每段list的大小
* @return List<<List<T>>
*/
public static <T> List<List<T>> splitList(List<T> list, int pageSize) {
int listSize = list.size();
int page = (listSize + (pageSize - 1)) / pageSize;// 页数
List<List<T>> listArray = new ArrayList<List<T>>();// 创建list数组,用来保存分割后的list
for (int i = 0; i < page; i++) { // 按照数组大小遍历
List<T> subList = new ArrayList<T>(); // 数组每一位放入一个分割后的list
for (int j = 0; j < listSize; j++) {// 遍历待分割的list
int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;// 当前记录的页码(第几页)
if (pageIndex == (i + 1)) {// 当前记录的页码等于要放入的页码时
subList.add(list.get(j)); // 放入list中的元素到分割后的list(subList)
}
if ((j + 1) == ((j + 1) * pageSize)) {// 当放满一页时退出当前循环
break;
}
}
listArray.add(subList);// 将分割后的list放入对应的数组的位中
}
return listArray;
}
/**
* list<Integer>转换成字符串
**/
public static String getStringFromIntegerList(List<Integer> list) {
String str=null;
if(CollectionUtils.isNullOrEmpty(list)) {
StringBuffer strBf = new StringBuffer();
list.stream().forEach(m -> strBf.append(m).append(ConstUtils.CHAR_COMMA));
str= strBf.toString().substring(0, strBf.length() - 1);
}
return str;
}
/**
* list<Integer>转换成字符串
**/
public static String getStringFromStringList(List<String> list) {
String str=null;
if(CollectionUtils.isNullOrEmpty(list)) {
StringBuffer strBf = new StringBuffer();
list.stream().forEach(m -> strBf.append(m).append(ConstUtils.CHAR_COMMA));
str= strBf.toString().substring(0, strBf.length() - 1);
}
return str;
}
/**
* 返回a与b的交集的新List.
*/
public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
List<T> list = new ArrayList<T>();
for (T element : a) {
if (b.contains(element)) {
list.add(element);
}
}
return list;
}
}