package com.xzx.gc.util;
|
|
import cn.hutool.core.bean.BeanUtil;
|
import cn.hutool.core.collection.CollUtil;
|
import cn.hutool.core.date.DateUtil;
|
import cn.hutool.core.lang.hash.Hash32;
|
import cn.hutool.core.util.ReflectUtil;
|
import lombok.experimental.UtilityClass;
|
|
import java.util.ArrayList;
|
import java.util.Collection;
|
import java.util.List;
|
|
@UtilityClass
|
public class CollUtils {
|
|
|
public <T> List<List<T>> groupByField(Collection<T> collection, final String fieldName) {
|
return groupByField(collection,fieldName,"1");
|
}
|
|
/**
|
* 根据元素的指定字段名分组,非Bean都放在第一个分组中
|
*
|
* @param <T> 元素类型
|
* @param collection 集合
|
* @param fieldName 元素Bean中的字段名,非Bean都放在第一个分组中
|
* @param type 1:将时间转换成天分组
|
* @return 分组列表
|
*/
|
public <T> List<List<T>> groupByField(Collection<T> collection, final String fieldName,String type) {
|
return CollUtil.group(collection, new Hash32<T>() {
|
private final List<Object> fieldNameList = new ArrayList<>();
|
|
@Override
|
public int hash32(T t) {
|
if (null == t || false == BeanUtil.isBean(t.getClass())) {
|
// 非Bean放在同一子分组中
|
return 0;
|
}
|
Object value = ReflectUtil.getFieldValue(t, fieldName);
|
if("1".equals(type)){
|
if(value==null){
|
value=DateUtil.now();
|
}
|
value=DateUtil.parseDateTime(value.toString()).toDateStr();
|
}
|
int hash = fieldNameList.indexOf(value);
|
if (hash < 0) {
|
fieldNameList.add(value);
|
return fieldNameList.size() - 1;
|
} else {
|
return hash;
|
}
|
}
|
});
|
}
|
}
|