【问题标题】:Sorting my HashMap by Key [duplicate]按键排序我的HashMap [重复]
【发布时间】:2014-08-29 08:35:55
【问题描述】:

我有以下HashMap

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

其中使用以下键:

static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_TITLE = "title";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_TIME = "pubDate";

然后我使用这段代码来填充哈希图。

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 格式的每篇文章的发布时间。

我想知道如何通过键 KEY_TIME 对这个 hashmap 进行排序,以便顶部的文章是最新的,底部的文章是最旧的。

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

【问题讨论】:

  • 请在提问前做一些研究......这里被问了很多次,我很确定谷歌会给你一些答案
  • 您为什么不使用TreeMap?它已经排序了。
  • 我很确定他想得到这个ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems(通过它的价值之一——比如hashmapItem [“Column”])而不是HashMaps本身......我很确定TreeMap 在同一 TreeMap 实例中的键排序,而不是 ArrayList 中的多个 TreeMap
  • 我曾尝试使用 TreeMap,但在将哈希图转换为树图时发现了一些问题。不过,我会再看看,谢谢。
  • 如果您真的需要为此坚持使用 ArrayList(或一般的 List),一种选择是创建一个数据持有者类并使其通过 KEY_TIME 进行比较(而不是使用 Map)。跨度>

标签: java sorting hashmap


【解决方案1】:

如果我的问题是正确的,因为您希望根据项目添加时间对添加到单个哈希图中的项目详细信息进行排序,那么您实际上必须对包含项目集合而不是单个哈希图的数组列表进行排序。您可以通过创建自定义比较器类来做到这一点,如下所示:-

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());

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 2023-03-17
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2011-12-28
    • 2015-03-30
    • 1970-01-01
    • 2011-12-24
    相关资源
    最近更新 更多