java 8分組排序 多重分組排序 treeMap 自定義排序

// 源數據
ArrayList<GateScanCodeRecord> objects = new ArrayList<>();
objects.add(new GateScanCodeRecord().setMonth("2020-07").setDay("2020-07-12"));
objects.add(new GateScanCodeRecord().setMonth("2020-06").setDay("2020-06-14"));
objects.add(new GateScanCodeRecord().setMonth("2020-06").setDay("2020-06-12"));
objects.add(new GateScanCodeRecord().setMonth("2020-05").setDay("2020-05-17"));
objects.add(new GateScanCodeRecord().setMonth("2020-05").setDay("2020-05-12"));

分組 (無序)

Map<String, List<GateScanCodeRecord>> collect1 = objects.parallelStream().collect(Collectors.groupingBy(GateScanCodeRecord::getMonth));

在這裏插入圖片描述

分組(有序 TreeMap)

TreeMap<String, List<GateScanCodeRecord>> collect2 = objects.parallelStream().collect(Collectors.groupingBy(GateScanCodeRecord::getMonth, TreeMap::new, Collectors.toList()));

在這裏插入圖片描述

分組(有序 TreeMap)

TreeMap<String, List<GateScanCodeRecord>> collect3 =
            objects.parallelStream().collect(
                Collectors.groupingBy(
                    GateScanCodeRecord::getMonth,
                   () -> new TreeMap<>((o1, o2) -> Math.toIntExact(Long.parseLong(o2) - Long.parseLong(o1))),
                    Collectors.toList()));

在這裏插入圖片描述

兩層排序(按月分組排序,月下的數據按天分組並排序)

TreeMap<String, TreeMap<String, List<GateScanCodeRecord>>> collect = objects.stream()
            .collect(
                Collectors.groupingBy(
                    GateScanCodeRecord::getMonth,
                    () -> new TreeMap<>((o1, o2) -> Math.toIntExact(Long.parseLong(o2) - Long.parseLong(o1))),
                    Collectors.groupingBy(
                        GateScanCodeRecord::getDay,
                       () -> new TreeMap<>((o1, o2) -> Math.toIntExact(Long.parseLong(o2) - Long.parseLong(o1))),
                        Collectors.toList()
                    )
                )
            );

在這裏插入圖片描述

注: 源數據並未進行排序操作

優化

源數據進行排序操作操作後,可以使用 LinkedHashMap

特別聲明: 代碼中重寫了TreeMap的排序,偷懶,故隨便寫的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章