public static void printMapAsMatrix(Map<Integer, Integer> map, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Integer v = map.get(size * i + j);
if (v == null)
v = 0;
System.out.printf("%1$-5s", v);
}
System.out.println();
}
}
This solution pads every cell so that it occupied 5 chars. You may change this if needed. The idea is to create the full matrix by scanning all cells (0..size-1)x(0..size-1), and fetching the value of that cell from the map. Line i and column j should be transformed to key=size * i + j, because we have to skip i lines and j items in the current line. Non existent items are converted to 0.