TreeMap
如何排序?例如,您具有以下 map :
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
那么,如果不是按字母顺序排列,那是什么呢?
最佳答案
它不仅按字母顺序,而且还区分大小写。
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