views:

42

answers:

2

I need to convert a navigable map to a 2d String array.Below given is a code from an answer to one of my previous question.

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!

I have to convert this map to a 2d String array:

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

Is there a fast and elegant way to do this?

+2  A: 

Best bet is just to iterate through the Map and create an array for each entry, the troublesome part is generating things like "0-11" since this requires looking for the next highest key...but since the Map is sorted (because you're using a TreeMap) it's no big deal.

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++;
}
Mark E
Thanks,it works.I gave a break when nextKey is null.I'll just wait a little while longer and see if any one else gives a better one.
Emil
+1  A: 

Hello, you can create two Arrays, one with the keys and one with the values in an "elegant way" then you can construct an String[][] using this two arrays.

// 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];
}
Torres