自定义分组
/**
* 集合分组工具类
*
* @autor WYH
*/
public class GroupUtils {
/**
* 集合分组算法封装。
*
* @param colls 待分组的集合
* @param gb 分组依据
* @return Map<T, List < E>>
*/
public static final <T extends Comparable<T>, E> Map<T, List<E>> group(Collection<E> colls, GroupBy<T> gb) {
if (colls == null || colls.isEmpty()) { // 分组集合为空
return null;
}
if (gb == null) {// 分组依据为空
return null;
}
Map<T, List<E>> map = new HashMap<T, List<E>>();
Iterator<E> it = colls.iterator();
while (it.hasNext()) {
E e = it.next();
T t = gb.groupby(e);
if (map.containsKey(t)) {
map.get(t).add(e);
} else {
List<E> list = new ArrayList<E>();
list.add(e);
map.put(t, list);
}
}
return map;
}
/**
* 返回空数据
*
* @param colls
* @param gb
* @param <T>
* @param <E>
* @return
*/
public static <T extends Comparable<T>, E> Map<T, List<E>> groupNew(Collection<E> colls, GroupBy<T> gb) {
if (colls == null || colls.isEmpty()) { // 分组集合为空
return new HashMap<>();
}
if (gb == null) {// 分组依据为空
return new HashMap<>();
}
Map<T, List<E>> map = new HashMap<T, List<E>>();
Iterator<E> it = colls.iterator();
while (it.hasNext()) {
E e = it.next();
T t = gb.groupby(e);
if (map.containsKey(t)) {
map.get(t).add(e);
} else {
List<E> list = new ArrayList<E>();
list.add(e);
map.put(t, list);
}
}
return map;
}
}
/**
* 分组依据接口
*
* @autor WYH
* @since 2019-08-22
*/
public interface GroupBy<T> {
T groupby(Object obj);
}
测试
public class GroupTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("name","张三");
map.put("age","20");
map.put("dept","开发");
Map<String, String> map1 = new HashMap<>();
map1.put("name","李四");
map1.put("age","21");
map1.put("dept","人事");
Map<String, String> map2 = new HashMap<>();
map2.put("name","王五");
map2.put("age","22");
map2.put("dept","行政");
Map<String, String> map3 = new HashMap<>();
map3.put("name","米卡");
map3.put("age","22");
map3.put("dept","人事");
List<Map<String, String>> list = new ArrayList<>();
list.add(map);
list.add(map1);
list.add(map2);
list.add(map3);
// 将数据分组
Map<String, List<Map<String, String>>> group = GroupUtils.group(list, new GroupBy<String>() {
@Override
public String groupby(Object obj) {
if (obj instanceof Map) {
Map<String, String> map = (Map<String, String>) obj;
return (String) map.get("age");
}
return null;
}
});
System.out.println(group);
}
}
打印结果:
{22=[{name=王五, dept=行政, age=22}, {name=米卡, dept=人事, age=22}], 20=[{name=张三, dept=开发, age=20}], 21=[{name=李四, dept=人事, age=21}]}
Java8
//按照多个属性分组,key为多个属性合
Map<String, List<Map<String, String>>> collect = list.stream().collect(Collectors.groupingBy(e -> e.get("dept") + e.get("age")));
System.out.println(collect);
//按照多个属性分组,key为单个属性合
Map<String, Map<String, List<Map<String, String>>>> result = list.stream().collect(Collectors.groupingBy(e -> e.get("dept"), Collectors.groupingBy(e -> e.get("age"))));
System.out.println(result);