简体   繁体   中英

How to convert a map to two dimensional array in java?

I want to add all key/value of a Map to a two dimensional array.

Does any body know a better way? I did as below but i search for a better way.

    Map<String, String> memoMap = AvoCollection.getMemoMap();
    String[][] data = new String[memoMap.size()][2];
    int ii =0;
    for(Map.Entry entry : memoMap.entrySet()){
        data[ii][0] = entry.getKey().toString();
        data[ii][1] = entry.getValue().toString();
        ii++;
    }
    final DefaultTableModel model = new DefaultTableModel(data,new String[]{"Memo","ID"});

This may be marginally better, but not by much:

Map<String,String> memoMap = AvoCollection.getMemoMap();
String[][] data = new String[memoMap.size()][];
int ii =0;
for(Map.Entry<String,String> entry : memoMap.entrySet()){
    data[ii++] = new String[] { entry.getKey(), entry.getValue() };
}
final DefaultTableModel model = new DefaultTableModel(data,new String[]{"Memo","ID"});

After declaring Map.Entry<String,String> you can stop calling toString ; you can also create a two-element array with an aggregate.

Are you open to use Guava Library from google. http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained . Then you can try using MultiMap which will return you the sets for keys and values which can easily be converted into array. Try looking into this library it has lots of cool functionals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM