java8模拟grouby方法

 public class ListUtils{
    /**
     * list 集合分组
     *
     * @param list    待分组集合
     * @param groupBy 分组Key算法
     * @param <K>     分组Key类型
     * @param <V>     行数据类型
     * @return 分组后的Map集合
     */
    public static <K, V> Map<K, List<V>> groupBy(List<V> list, GroupBy<K, V> groupBy) {
        return groupBy((Collection<V>) list, groupBy);
    }
    /**
     * list 集合分组
     *
     * @param list    待分组集合
     * @param groupBy 分组Key算法
     * @param <K>     分组Key类型
     * @param <V>     行数据类型
     * @return 分组后的Map集合
     */
    public static <K, V> Map<K, List<V>> groupBy(Collection<V> list, GroupBy<K, V> groupBy) {
        Map<K, List<V>> resultMap = new LinkedHashMap<K, List<V>>();

        for (V e : list) {

            K k = groupBy.groupBy(e);
            if (resultMap.containsKey(k)) {
                resultMap.get(k).add(e);
            } else {
                List<V> tmp = new LinkedList<V>();
                tmp.add(e);
                resultMap.put(k, tmp);
            }
        }
        return resultMap;
    }
    /**
     * List分组
     *
     * @param <K> 返回分组Key
     * @param <V> 分组行
     */
    public interface GroupBy<K, V> {
        K groupBy(V row);
    }
}

  例子:

Map<String,List<Student>> resMap = ListUtils.groupBy(studentList,new ListUtils.GroupBy<String,Student>(){
@Override
public String groupBy(Student row){
String ktrq = row.getKtrq();
String ktrqStr = "";
if(ktrq != null){
ktrqStr = ktrq.substring(0,4);
}
return ktrqStr;
}
});

说明:

1.上述例子中,studentList 为学生集合别名,实体类为Student ,其中有个属性为ktrq (开通日期);
2. ktrq 在数据库为date 类型,且实体类定义为字符串类型,格式为 YYYY-MM-DD,使用substring() 截取,得到对应的年份,然后按照年份分组,最后得到对应的Map集合;

  



原文地址:https://www.cnblogs.com/airycode/p/10435118.html