2010-08-26 27 views
1

我需要一個導航地圖轉換爲2D字符串array.Below給出的是從answer代碼我剛纔的問題之一。如何將NavigableMap的轉換爲String [] []

NavigableMap<Integer,String> map = 
     new TreeMap<Integer, String>(); 

map.put(0, "Kid"); 
map.put(11, "Teens"); 
map.put(20, "Twenties"); 
map.put(30, "Thirties"); 
map.put(40, "Forties"); 
map.put(50, "Senior"); 
map.put(100, "OMG OMG OMG!"); 

System.out.println(map.get(map.floorKey(13)));  // Teens 
System.out.println(map.get(map.floorKey(29)));  // Twenties 
System.out.println(map.get(map.floorKey(30)));  // Thirties 
System.out.println(map.floorEntry(42).getValue()); // Forties 
System.out.println(map.get(map.floorKey(666))); // OMG OMG OMG! 

我有這個地圖轉換爲二維String數組:

{ 
{"0-11","Kids"}, 
{"11-20","Teens"}, 
{"20-30","Twenties"} 
... 
} 

是否有一個快速和優雅的方式來做到這一點?

+0

' 「媽呀媽呀媽呀!」「 - LOL難怪片段看起來很熟悉... – polygenelubricants 2010-08-26 11:45:48

+0

@poly:有一個更好的解決方案? – Emil 2010-08-26 11:48:14

+0

@Emil:你是否必須將數據表示爲一個String [] []'?怎麼樣一個普通的'List >'而不是?你可以得到'MappedInterval.start()'和'.END()'和'.value的()',你可以'@ Override'的'的toString()'打印像'[開始結束] = >價值'或類似的東西。基本上我不認爲你可以想出任何更好的算法來轉換爲'String [] []',但是比起'String [] []'有更好的表示,我可以給出這個片段要做到這一點。 – polygenelubricants 2010-08-26 11:54:29

回答

2

最好的辦法就是通過地圖迭代,併爲每個條目的數組,麻煩的部分產生喜歡的東西「0-11」,因爲這需要尋找下一個最高鍵...但由於地圖是排序(因爲你使用的是TreeMap),這沒什麼大不了的。

String[][] strArr = new String[map.size()][2]; 
int i = 0; 
for(Entry<Integer, String> entry : map.entrySet()){ 
    // current key 
    Integer key = entry.getKey(); 
    // next key, or null if there isn't one 
    Integer nextKey = map.higherKey(key); 

    // you might want to define some behavior for when nextKey is null 

    // build the "0-11" part (column 0) 
    strArr[i][0] = key + "-" + nextKey; 

    // add the "Teens" part (this is just the value from the Map Entry) 
    strArr[i][1] = entry.getValue(); 

    // increment i for the next row in strArr 
    i++; 
} 
+0

謝謝,它的工作原理。當nextKey爲null時我休息了一會兒。我會稍等一會兒,看看其他人是否會給出更好的結果。 – Emil 2010-08-26 11:06:03

1

可以創建兩個陣列,一個與所述鍵和一個與處於「優雅的方式」的值,則使用該兩個陣列可以構造一個字符串[] []。

// Create an array containing the values in a map 
Integer[] arrayKeys = (Integer[])map.keySet().toArray(new Integer[map.keySet().size()]); 
// Create an array containing the values in a map 
String[] arrayValues = (String[])map.values().toArray(new String[map.values().size()]); 

String[][] stringArray = new String[arrayKeys.length][2]; 
for (int i=0; i < arrayValues.length; i++) 
{ 
     stringArray[i][0] = arrayKeys[i].toString() + (i+1 < arrayValues.length ? " - " + arrayKeys[i+1] : ""); 
     stringArray[i][1] = arrayValues[i]; 
} 
相關問題