我不确定我应该将我的数组String [][]
初始化为什么。
如果我将它设置为treeMap的大小,那么就有一个NPE。
String [][] ans = new String[size][];
所以我初始化为比预期更大但是我的数组中有空值。
目前我的treeMap是 {C = [E],M = [F,B],S = [F,B],T = [F,B,L],TD = [E,L] ,W = [E,L],Z = [F]}
我希望它是
[[C,E],[M,F,B],[S,F,B] ....]
import java.util.*;
public class Copy {
public static String[][] oMI(String[][] m){
//ans[0][0]= "test";
Map<String, List<String>> map = new HashMap<>();
int length = m.length;
for (int i=0; i < m.length;i++){
for (int j=1; j < m[i].length;j++){
String key = m[i][j];
map.computeIfAbsent(key, k-> new ArrayList<String>()).add(m[i][0]);
}
}
Map<String,List<String>> treeMap = new TreeMap<String, List<String>>(map);
System.out.println(treeMap);
int size = treeMap.size();
String [][] ans = new String[20][20];
int l = 0;
int s = 0;
String ing = "";
for (Map.Entry<String,List<String>> entry: treeMap.entrySet()){
s = entry.getValue().size();
if (entry.getKey() !=null)
ing = entry.getKey();
else ing ="null";
ans[l][0] = ing;
int mn = 0;
for (String v : entry.getValue()) {
ans[l][mn] = v;
l++;
mn++;
}
}
return ans;
}
public static void main(String[] args){
String [][] ma =
{
{"F", "T", "Z", "S", "M"},
{"E", "C", "W", "TD"},
{"B", "M", "S", "T"},
{"L", "W", "T", "TD"}
};
oMI(ma);
}
}
答案 0 :(得分:0)
如果您需要不使用流的解决方案,可以使用以下内容:
int size = treeMap.size();
String [][] ans = new String[size][]; //initialize the known dimension only
int arrayRow = 0;
for (Map.Entry<String,List<String>> entry: treeMap.entrySet()){
int rowSize = entry.getValue().size() + 1;
String[] tempArray = new String[rowSize]; //an temp array to hold key + vlaues
tempArray[0] = entry.getKey(); //add key to temp array
int mn = 1;
for (String s : entry.getValue()) { tempArray[mn++] = s; } //add values to temp array
ans[arrayRow++] = tempArray; //add temp array to output array
}
return ans;