首页 > 解决方案 > 在 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));

标签: lambdajava-8functional-programmingjava-stream

解决方案


然后使用 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));

推荐阅读