如何将Navigablemap转换为String [] []

时间:2010-08-26 10:41:00

标签: java string map multidimensional-array

我需要将一个可导航的地图转换为二维的String数组。给出的是从answer到我之前的一个问题的代码。

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!

我必须将此地图转换为2d String数组:

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

有没有快速而优雅的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

最好的办法是迭代Map并为每个条目创建一个数组,麻烦的部分是生成类似“0-11”的东西,因为这需要查找下一个最高的键...但是因为Map已经排序(因为你正在使用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++;
}

答案 1 :(得分:1)

你可以创建两个Arrays,一个带有键,一个带有“优雅方式”的值,然后你可以用这两个数组构造一个String [] []。

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