【发布时间】:2021-12-15 02:13:16
【问题描述】:
问题:
-
我有一个
Map<LocalDate, Integer>,我想使用LocalDate按周对这些地图元素进行分组,并使用 Java 8 Stream 按周查找每个分组值的最大值。 -
我目前遇到无法将密钥转换回流中的
LocalDate对象的问题,因为我没有必要的数据字段来将LocalDate的对象创建到地图中。 -
如果我不将其转换为
LocalDate并将其保留为String,我将无法使用TreeMap使用键按自然顺序排列键值。 -
如果我在对数据进行分组时未将月份包含在
DateTimeFormatter.ofPattern中,则两年之间的周数可能会重叠。 -
如果我只使用周数整数作为流中地图的输出,则按周分组的值将与另一年的周数混合并重叠,即 2020-2021 和第 1 周。
问题:
- 如何使用 java 流获得每周值的最大值?
数据集:
Map<LocalDate,Integer> CumulativeGarbageWasteDate = new HashMap<LocalDate,Integer>();
CumulativeGarbageWasteDate.put(LocalDate.parse(("5/2/2020"),DateTimeFormatter.ofPattern("[M/d/yyyy][M/d/yy]")),2400);
CumulativeGarbageWasteDate.put(LocalDate.parse(("12/24/20"),DateTimeFormatter.ofPattern("M/d/yy")),140);
CumulativeGarbageWasteDate.put(LocalDate.parse(("5/2/20"),DateTimeFormatter.ofPattern("M/d/yy")),2400);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/1/21"),DateTimeFormatter.ofPattern("M/d/yy")),182);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/2/21"),DateTimeFormatter.ofPattern("M/d/yy")),203);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/3/21"),DateTimeFormatter.ofPattern("M/d/yy")),321);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/3/21"),DateTimeFormatter.ofPattern("M/d/yy")),421);
CumulativeGarbageWasteDate.put(LocalDate.parse(("5/2/2021"),DateTimeFormatter.ofPattern("[M/d/yyyy][M/d/yy]")),2400);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/6/21"),DateTimeFormatter.ofPattern("M/d/yy")),1200);
CumulativeGarbageWasteDate.put(LocalDate.parse(("01/31/21"),DateTimeFormatter.ofPattern("M/d/yy")),2400);
代码:
private static Map<LocalDate, Integer> sumByWeek (Map<LocalDate,Integer> CumulativeGarbageWasteDate){
DateTimeFormatter formatter3 = new DateTimeFormatterBuilder().appendPattern("w/M/YY").parseDefaulting(ChronoField.DAY_OF_WEEK,DayOfWeek.FRIDAY.getValue()).toFormatter();
return CumulativeGarbageWasteDate
.entrySet()
.stream()
.collect(Collectors.groupingBy(
row-> LocalDate.parse(row.getKey().format(DateTimeFormatter.ofPattern("w/M/YY")),formatter3),
TreeMap::new,
Collectors.reducing(0, x->x.getValue(),Math::max)));
}
错误:
这是我在运行代码时遇到的错误。
java.time.format.DateTimeParseException: Text '5/2/20' could not be parsed: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 2 derived from 2020-01-31
【问题讨论】:
-
欢迎来到 Stack Overflow。我强烈建议您使用 tour 了解 Stack Overflow 的工作原理并阅读 How to Ask。这将帮助您提高问题的质量。对于每个问题,请显示您尝试过的尝试以及您从尝试中得到的错误消息。
-
@McPringle 嗨,我已经更新了错误内容以及之前添加的尝试,并更新了标题以便更好地澄清。感谢您的反馈。
-
如果
Hashmap<K,V>不支持重复键导致两个日期相同怎么办 -
您是否考虑过 this 在给定 LocalDate 对象的情况下获取一年中一周的 int 值的方法?
-
@ArvindKumarAvinash 你知道它还没有完全解决吗?为什么我要发布一个我没有得到正确答案的问题的答案?
标签: java java-8 java-stream