如何在Java中对Map的键进行排序? [英] How can I sort the keys of a Map in Java?

查看:100
本文介绍了如何在Java中对Map的键进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,我对Java不太满意。我有一个Map,我想按排序顺序获取一个列表或一些键,所以我可以迭代它们。

This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.

推荐答案

使用 TreeMap ,这是 SortedMap 接口的实现。它按排序顺序显示其键。

Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.

Map<String, Object> map = new TreeMap<String, Object>();
/* Add entries to the map in any order. */
...
/* Now, iterate over the map's contents, sorted by key. */
for (Map.Entry<String, ?> entry : map.entrySet()) {
  System.out.println(entry.getKey() + ": " + entry.getValue());
}

如果你正在处理另一个没有按照你喜欢的方式排序的Map实现,你可以将它传递给 TreeMap的>构造函数用于创建带有排序键的新地图。

If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.

void process(Map<String, Object> original) {
  Map<String, Object> copy = new TreeMap<String, Object>(original);
  /* Now use "copy", which will have keys in sorted order. */
  ... 
}

A TreeMap 适用于实现 Comparable 接口的任何类型的密钥,将它们置于自然顺序中。对于不是 Comparable 的键,或者其自然顺序不是您需要的键,您可以实现自己的 Comparator 并在< a href =http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)rel =noreferrer>构造函数。

A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.

这篇关于如何在Java中对Map的键进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆