Helius
2021-06-29 5252d1396e21a16774be699a5ba1c8d39c14a22e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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;
                }
            }
        });
    }
}