树状图如何排序

2022-09-02 11:47:23

如何排序?例如,您有以下地图:TreeMap

TreeMap<String, Integer> treemap = new TreeMap<>();
treemap.put("lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);

Iterator ittwo = treemap.entrySet().iterator();
    while (ittwo.hasNext()) {
    Map.Entry pairs = (Map.Entry)ittwo.next();
    System.out.println(pairs.getKey() + " = " + pairs.getValue());
    ittwo.remove();
}

其输出为:

Jesper = 3
Marc = 2
lol = 1

那么,如果它不是按字母顺序排列的,那么它是什么呢?


答案 1

它不仅按字母顺序排列,而且还区分大写/下写。

TreeMap<String, Integer> treemap = new TreeMap<String, Integer>();
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);

输出:

Jesper = 3
Lol = 1
Marc = 2
jesper1 = 3
lol1 = 1
marc1 = 2

因此,如果您不需要它,则可以使用自定义比较器,并以小写形式比较字符串:

TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        return o1.toLowerCase().compareTo(o2.toLowerCase());
    }
});
treemap.put("Lol", 1);
treemap.put("Marc", 2);
treemap.put("Jesper", 3);
treemap.put("lol1", 1);
treemap.put("marc1", 2);
treemap.put("jesper1", 3);

输出:

Jesper = 3
jesper1 = 3
Lol = 1
lol1 = 1
Marc = 2
marc1 = 2

答案 2

正如JavaDoc中所述,“...根据其的自然顺序进行排序...”(强调的是我的)。TreeMap

因此,您的结果是正确的,因为小写字母在UTF“字母表”中是大写字母之后lM

如果您希望重写默认行为,可以向构造函数提供 。ComparatorTreeMap


推荐