lambda - 在 Java8 中使用 Lambda 表达式对地图进行排序
问题描述
我创建了一个带有 Comparator 的 Map 以按键排序,但是在填充 Map 后,在填充数据后没有应用任何顺序。
SimpleDateFormat byDay = new SimpleDateFormat("ddMMyyyy");
Map<String, DoubleSummaryStatistics> menuStatisticsXDay = new TreeMap<String, DoubleSummaryStatistics>(
new Comparator<String>() {
@Override
public int compare(String dateStr1, String dateStr12) {
Date date1 = new Date();
Date date2 = new Date();
try {
date1 = byDay.parse(dateStr1);
} catch (ParseException e) {
}
try {
date2 = byDay.parse(dateStr1);
} catch (ParseException e) {
}
return date1.compareTo(date2);
}
});
menuStatisticsXDay =
menuPrices.stream().sorted(comparing(MenuPrice::getUpdateDate))
.collect(Collectors.groupingBy(cp -> byDay.format(cp.getUpdateDate()),
Collectors.summarizingDouble(cp -> cp.getPriceInDouble())));
这样做会对键进行排序,但作为字符串,所以“06092018”将比“07082018”先,这就是为什么我想使用我的比较器,转换为日期并对其进行排序,然后“07082018”将比“06092018”先:
Map<String, DoubleSummaryStatistics> menuStatisticsXDay =
menuPrices.stream().sorted(comparing(MenuPrice::getUpdateDate))
.collect(Collectors.groupingBy(m -> byDay.format(m.getUpdateDate()),
Collectors.summarizingDouble(m -> m.getPriceInDouble())))
.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
解决方案
然后使用 LocalDate 而不是 String 作为键:
Map<LocalDate, DoubleSummaryStatistics> menuStatisticsXDay =
menuPrices.stream().sorted(comparing(MenuPrice::getUpdateDate))
.collect(Collectors.groupingBy(m -> m.getUpdateLocalDate(),
Collectors.summarizingDouble(m -> m.getPriceInDouble())))
.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
推荐阅读
- amp-html - AMP 未在移动设备中完全加载?
- python - 即使在主线程崩溃后,子线程也会继续运行
- macos - 在 OSX 上构建 mariadb-connector-c
- ubuntu - 安装 Sharp /usr/include/vips/vips8:35:25:致命错误:glib-object.h
- python-3.x - AttributeError:“Figure”对象没有属性“set_axes”
- angular - 路由器出口外的角组件
- java - 用户卸载我的应用后,Google Drive 应用文件夹会被删除吗?
- python - 谁能解释 tf.random_normal 和 tf.truncated_normal 形状参数?
- html - 内部下拉菜单上的引导折叠动画
- angularjs - 无法从angularjs中的facebook登录获取电子邮件