Java8 Stream分组并排序

时间:2025-04-09 10:44:58
@Data @AllArgsConstructor @NoArgsConstructor public class Customer { private String name; private TypeEnum type; private int age; } @Getter public enum TypeEnum { /** * 第一 */ First("甲类", 2), Second("乙类", 12), Three("丙类",0), Four("丁类",3), ; private String desc; /** * 优先级 */ private int priority; TypeEnum(String desc, int priority) { this.desc = desc; this.priority = priority; } } public class GroupByTest { @Test public void test() { List<Customer> customers = new ArrayList<>(); // 按照type 分组,组内 age 排序 customers.add(new Customer("张三", TypeEnum.First, 18)); customers.add(new Customer("赵六", TypeEnum.Second, 25)); customers.add(new Customer("李四", TypeEnum.Second, 22)); customers.add(new Customer("张一", TypeEnum.Three, 31)); customers.add(new Customer("王五", TypeEnum.Four, 45)); customers.add(new Customer("张二", TypeEnum.Four, 40)); // 如此分组,treeMap 默认排序会按照 TypeEnum 枚举顺序 TreeMap<TypeEnum, List<Customer>> treeMap = customers.stream().collect(Collectors.groupingBy(Customer::getType, TreeMap::new, Collectors.toList())); System.out.println("默认排序:" + treeMap); // 如果 treeMap 想要自定义排序,则可以这么做 TreeMap<TypeEnum, List<Customer>> treeMap2 = customers.stream().collect(Collectors.groupingBy(Customer::getType, GroupByTest::getCustomSortTreeMap, Collectors.toList())); for (Map.Entry<TypeEnum, List<Customer>> entry : treeMap2.entrySet()) { entry.getValue().sort(Comparator.comparing(Customer::getAge)); } System.out.println("自定义排序:" + treeMap2); // 按指定字段分组 Map<TypeEnum, List<Integer>> map3 = customers.stream().collect(Collectors.groupingBy(Customer::getType, Collectors.mapping(Customer::getAge, Collectors.toList()))); System.out.println("按指定字段分组:" + map3); TreeMap<TypeEnum, List<Customer>> treeMap4 = customers.stream().sorted(Comparator.comparing(Customer::getAge, Comparator.nullsLast(Integer::compareTo))) .collect(Collectors.groupingBy(Customer::getType, TreeMap::new, Collectors.toList())); System.out.println("排序后分组:" + treeMap4); } public static TreeMap<TypeEnum, List<Customer>> getCustomSortTreeMap() { return new TreeMap<>(Comparator.comparingInt(TypeEnum::getPriority)); }