如何在Java中按键对Map值进行排序?我有一个Map,它包含键和值的字符串。数据如下:“问题1”,“1”“问题9”、“1”“问题2”、“4”“问题5”、“2”我想根据地图的键对地图进行排序。所以,最后,我会question1, question2, question3…等等。最后,我试图从这个地图中得到两个字符串。第一个字符串:问题(按1.10顺序排列)第二个字符串:答案(与问题的顺序相同)现在我有以下几点:Iterator it = paramMap.entrySet().iterator();while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
questionAnswers += pairs.getKey() + ",";}这让我得到了一个字符串中的问题,但它们是不整齐的。
3 回答

开心每一天1111
TA贡献1836条经验 获得超13个赞
List sortedKeys=new ArrayList(yourMap.keySet());Collections.sort(sortedKeys);// Do what you need with sortedKeys.

慕勒3428872
TA贡献1848条经验 获得超6个赞
TreeMap
Map<String, String> map = new HashMap<>(); Map<String, String> treeMap = new TreeMap<>(map);for (String str : treeMap.keySet()) { System.out.println(str);}
添加回答
举报
0/150
提交
取消