java - 以 "MMMyyyy"为键对 map 进行排序

标签 java sorting hashmap simpledateformat treemap

我有一张 map ,其键采用 MMMyyyy 格式,我需要根据月份进行排序。 输入:

unsorted: {
 "Dec2010": 1,
 "Apr2010": 1,
 "Feb2010": 0,
 "Nov2010": 2,
 "Mar2010": 0,
 "Jun2010": 2,
 "Sep2010": 1,
 "May2010": 0,
 "Oct2010": 1,
 "Jul2010": 0,
 "Aug2010": 0,
 "Jan2010": 1
}

排序后应该是这样的:

sorted: {
 "Jan2010": 1
 "Feb2010": 0,
 "Mar2010": 0,
 "Apr2010": 1,
 "May2010": 0,
 "Jun2010": 2,
 "Jul2010": 0,
 "Aug2010": 0,
 "Sep2010": 1,
 "Oct2010": 1,
 "Nov2010": 2,
 "Dec2010": 1,     
}

目前我正在使用 TreeMap 按字母顺序对其进行排序,但我如何根据月份层次结构对其进行排序。

代码:

    Map<String, Integer> unsorted = new HashMap<>();
    unsorted.put("Dec2010", 1);
    unsorted.put("Apr2010", 1);
    unsorted.put("Feb2010", 0);
    unsorted.put("Nov2010", 2);
    unsorted.put("Mar2010", 0);
    unsorted.put("Jun2010", 2);
    unsorted.put("Sep2010", 1);
    unsorted.put("May2010", 0);
    unsorted.put("Oct2010", 1);
    unsorted.put("Jul2010", 0);
    unsorted.put("Aug2010", 0);
    unsorted.put("Jan2010", 1);

    System.out.println("\nSorted......");
    Map<String, Integer> sorted = new TreeMap<>(unsorted);
    for (Map.Entry<String, Integer> entry : sorted.entrySet()) {
        System.out.println("Key : " + entry.getKey()
                + " Value : " + entry.getValue());
    }

最佳答案

让我们尝试使用自定义比较器:

public class Main {

    public static void main(String[] args) {

        final SimpleDateFormat df = new SimpleDateFormat("MMMyyyy");

        Map<String, Integer> map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                String s1 = (String) o1;
                String s2 = (String) o2;
                try {
                    return df.parse(s1).compareTo(df.parse(s2));
                } catch (ParseException e) {
                    throw new RuntimeException("Bad date format");
                }
            };
        });

        map.put("Dec2011",1);
        map.put("Jan2011",0);
        map.put("Feb2011",1);
        map.put("Mar2011",0);
        map.put("Oct2011",1);
        map.put("Sep2011",0);

        for(Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

    }
}

输出:

Jan2011 -> 0
Feb2011 -> 1
Mar2011 -> 0
Sep2011 -> 0
Oct2011 -> 1
Dec2011 -> 1

关于java - 以 "MMMyyyy"为键对 map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998172/

相关文章:

java - 如何将顶级框架放置在另一个java中

java - JPA:带有 BLOB 列的 'SELECT DISTINCT'

java - 加快全计数排序的方法

algorithm - 关于散列 - 二次探测证明

java - 当同一程序在 JVM5 和 JVM6 中运行时,HashMap 中的项目顺序不同

Java - 两个哈希集随着时间的推移是否会发生类似的变化?

mysql - 表中的行顺序取决于相关表

matlab - 在MatLab中按虚部排序

php - 在php和wordpress中合并然后排序2个数组

java - 将 HashMap 值添加到 TreeSet 时出错