我有一个地图,有字符串的键和值。

数据如下所示:

“问题1”,“1” “question9”、“1” “问题2”、“4” “问题5”、“2”

我想根据键对映射进行排序。所以,最后,我将得到问题1,问题2,问题3,等等。

最终,我试图从这个Map中得到两个字符串:

第一串:问题(按顺序1 ..10) 第二串:答案(与问题顺序相同)

现在我有以下内容:

Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    questionAnswers += pairs.getKey() + ",";
}

这让我得到了一个字符串中的问题,但它们不是按顺序排列的。


当前回答

在Java 8中

将Map<K, V>按键排序,将键放入List<K>:

List<K> result = map.keySet().stream().sorted().collect(Collectors.toList());

要按键对Map<K, V>排序,将条目放入List<Map。进入< K、V > >:

List<Map.Entry<K, V>> result =
    map.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByKey())
       .collect(Collectors.toList());

最后但并非最不重要的:以语言环境敏感的方式对字符串排序-使用Collator (comparator)类:

Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY); // case insensitive collator

List<Map.Entry<String, String>> result =
    map.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByKey(collator))
       .collect(Collectors.toList());

其他回答

使用树地图!

以防你不想使用TreeMap:

public static Map<Integer, Integer> sortByKey(Map<Integer, Integer> map) {
    List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
    list.sort(Comparator.comparingInt(Map.Entry::getKey));
    Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
    list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
    return sortedMap;
}

此外,如果您想要根据值对映射进行排序,只需更改map。入口::getKey映射。入口::getValue。

如果你不能使用TreeMap,在Java 8中,我们可以使用collector中的toMap()方法,该方法接受以下参数:

Keymapper:生成密钥的映射功能 Valuemapper:生成值的映射函数 mergeFunction:一个归并函数,用于解决与相同键相关联的值之间的冲突 mapSupplier:返回一个新的空Map的函数 结果将被插入。

Java 8实例

Map<String, String> sample = new HashMap<>(); // Push some values to map
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
                    .sorted(Map.Entry.<String, String>comparingByKey().reversed())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map<String, String> newMapSortedByValue = sample.entrySet().stream()
                        .sorted(Map.Entry.<String, String>comparingByValue().reversed())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

我们可以修改这个例子,使用自定义比较器,并根据键进行排序:

Map<String, String> newMapSortedByKey = sample.entrySet().stream()
                .sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

假设TreeMap不适合你(假设你不能使用泛型):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String str : map.keySet()) {
  list.add(str);
}

Collections.sort(list);

for (String str : list) {
  System.out.println(str);
}