Java 按键对HashMap进行排序

Java 按键对HashMap进行排序,java,sorting,hashmap,Java,Sorting,Hashmap,我有下面的HashMap: 然后我使用这段代码来填充hashmap HashMap<String, String> map = new HashMap<String, String>(); map.put(KEY_ID, parser.getValue(e, KEY_ID)); //Get the title of the article. map.put(KEY_NAME, parser.getValue(e, KEY_TITLE)); //Get the descr

我有下面的HashMap:

然后我使用这段代码来填充hashmap

HashMap<String, String> map = new HashMap<String, String>();

map.put(KEY_ID, parser.getValue(e, KEY_ID));
//Get the title of the article.
map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
//Get the description of the article.
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
//Add the keys to the hashmap.
menuItems.add(map);
等等

我有一个键,叫做key_TIME,它以16:30的格式存储每篇文章的发布时间

我想知道如何按键时间对这个hashmap进行排序,以便顶部的artcicles是最新的,底部的artcicles是最旧的


我知道以前有人问过这个问题,但是我找不到一个解决方案来解释Hashmap之前的ArrayList。

如果我正确回答了您的问题,因为您希望根据项目添加时间对单个Hashmap中添加的项目详细信息进行排序,那么您实际上必须对包含项目集合而不是单个Hashmap的ArrayList进行排序。您可以通过如下方式创建自定义比较器类来完成此操作:-

class ItemEntryComparator implements Comparator<Map<String,String>> {

    static final String KEY_TIME = "pubDate";
    @Override
    public int compare(Map<String, String> o1, Map<String, String> o2) {        
        return o2.get(KEY_TIME).compareTo(o1.get(KEY_TIME));
    }

}

请在询问之前做一些调查。。。这里有人问了很多次,我很肯定谷歌会给你一些答案为什么你不使用TreeMap?它已经被排序了。我很确定他想通过它的一个值得到这个ArrayList menuItems,比如hashmapItem[Column],而不是HashMaps本身。。。我很确定,在同一个TreeMap实例中,TreeMap的键顺序在ArrayListI中不是多个TreeMap。我尝试过使用TreeMap,但在将hashmap转换为TreeMap时发现了一些问题。不过,我会再看一看,谢谢。如果你真的需要坚持使用ArrayList或List,一个选择是创建一个dataholder类,并使其按键时间进行比较,而不是使用映射。
HashMap<String, String> map = new HashMap<String, String>();

map.put(KEY_ID, parser.getValue(e, KEY_ID));
//Get the title of the article.
map.put(KEY_NAME, parser.getValue(e, KEY_TITLE));
//Get the description of the article.
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
//Add the keys to the hashmap.
menuItems.add(map);
class ItemEntryComparator implements Comparator<Map<String,String>> {

    static final String KEY_TIME = "pubDate";
    @Override
    public int compare(Map<String, String> o1, Map<String, String> o2) {        
        return o2.get(KEY_TIME).compareTo(o1.get(KEY_TIME));
    }

}
Collections.sort(menuItems, new ItemEntryComparator());