This is a very generic question. I have a hashmap and I want to print it in a tabular format dynamically without knowing the size of the contents beforehand. The table should be well spaced just like we see in a Db query result. Are there any libraries/utilities which directly helps in this type of conversion? Or does JAVA have some intrinsic functions which I could make use of?
The code which I have written is a very naive one, and does not cater to dynamic length of the strings. I need the rows to be aligned also.
StringWriter returnString = new StringWriter();
Map<String,HashMap<String, String>> hashMap = new HashMap<String, HashMap<String, String>>();
for (Entry e : hashMap.entrySet()) {
HashMap<String, Number> hm = (HashMap<String, Number>) e.getValue();
String key = (String) e.getKey();
returnString.append("|\t").append(key).append("\t|");
for (Entry en : hm.entrySet()){
returnString.append("|\t").append((String) en.getValue()).append("\t|");
}
returnString.append("\r\n");
}
return returnString.toString();
The output should be like this irrespective of the strings length
s1 | s3 | s4
askdkc | asdkask | jksjndan
It looks like you already have the iteration figured out and are just working on the formatting. You could put it into a TableModel, and let the JTable handle the tabular formatting.
You could select fixed column widths or iterate once over the entries to find the maximum length of each column, then again to print them with appropriate padding.
Another option would be to extend HashMap so that it records the longest key and value as entries are added:
Note this ignores the obvious case where you also remove items–depending on your usage pattern, you’ll have to do a little or a lot more work if you also want to shrink the columns when removing entries with the longest keys/values.