javastringdictionarymultidimensional-array

How to convert a Navigablemap to String[][]


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, "Kids");
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?


Solution

  • 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++;
    }