I'm not sure what I should initialize my array String [][]
ans to be.
If I set it to be the size of the treeMap then there's a NPE.
String [][] ans = new String[size][];
So I initialized to be bigger than expected but then there are nulls in my array.
Currently my treeMap is {C=[E], M=[F, B], S=[F, B], T=[F, B, L], TD=[E, L], W=[E, L], Z=[F]}
I want it to be
[[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);
}
}
If you need a solution without using streams, you can use the following :
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;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments