// 源數據
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的排序,偷懶,故隨便寫的