2016-03-20 36 views
0

我有以下的Java代碼excert。我期待看到按排序方式打印的鍵(因爲我正在使用TreeMap),但它不會對鍵進行排序。我錯過了什麼?TreeMap迭代不給我排序的鍵

CODE:

public class TreeMapTest { 
    static TreeMap<String,String> li=new TreeMap<String,String>(); 

    static void readAndPrint(){ 
     for (Map.Entry<String, String> entry:li.entrySet()){ 
      System.out.println(entry); 
     } 

    } 
    public static void main(String[] args) { 
     for (int i=0;i<10;i++){ 
      String key = String.valueOf(new Random().nextInt(100)); 
      String item = UUID.randomUUID().toString().substring(30); 
      li.put(key,item); 
      System.out.println(MessageFormat.format("inserting ({0},{1})",key,item)); 
     } 

     readAndPrint(); 
    } 
} 

輸出示例:

inserting (7,f4b66a) 
inserting (2,5f417d) 
inserting (51,90bb9f) 
inserting (99,4bfb73) 
inserting (41,a4e9d5) 
inserting (14,9286d6) 
inserting (44,ec4fbd) 
inserting (58,e7dd3a) 
inserting (69,c54e66) 
inserting (0,d1fbfe) 
0=d1fbfe 
14=9286d6 
2=5f417d 
41=a4e9d5 
44=ec4fbd 
51=90bb9f 
58=e7dd3a 
69=c54e66 
7=f4b66a 
99=4bfb73 

正如你看到的,我沒有得到排序的元素(我有時輸出排序,有時有它沒有排序如上!)。我錯過了什麼或誤解?

回答

6

他們排序,按照字符串的默認排序順序。字符串按照字典順序排列,因此"14"被認爲小於"2"

如果你想要數字排序的順序,你應該已經使用整數而不是字符串。

1

由於地圖是字符串(第一個字符爲1 < 4,其他字符依此類推),因此地圖按字典順序排列鍵。

最簡單的方法是讓鍵作爲Integer S:

TreeMap<Integer,String> li=new TreeMap<>(); 

這將避免不必要的需要使用String.valueOf的整數轉換。

1

如果你想要基於Integer的比較,那麼你需要在地圖上有Integer鍵。更改

static TreeMap<String,String> li=new TreeMap<String,String>(); 

static TreeMap<Integer,String> li=new TreeMap<Integer,String>(); 

和變化提出的方法:做這件事,同時仍然保持按鍵的

Integer key = new Random().nextInt(100); 
String item = UUID.randomUUID().toString().substring(30); 
li.put(key,item); 
1

一種方式爲String s就使用Treemap(Comparator)構造:

static TreeMap<String, String> li = new TreeMap<>(Comparator.comparing(Integer::valueOf)); 

當然,製作鑰匙Integer也適用。