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

数据如下所示:

“问题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() + ",";
}

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


当前回答

使用树地图!

其他回答

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

在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不适合你(假设你不能使用泛型):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

只需使用TreeMap:

new TreeMap<String, String>(unsortMap);

请注意,TreeMap是根据“键”的自然顺序进行排序的。

使用Java 8:

Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));