1

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
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1063185
  • 105
  • 2
  • 8

4 Answers4

1

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:

package com.example;

public class MyHashMap<K, V> extends java.util.HashMap<K, V> {

    private int maxKeyLength = 0;
    private int maxValueLength = 0;

    @Override
    public V put(K key, V value) {
        maxKeyLength = Math.max(maxKeyLength, key.toString().length());
        maxValueLength = Math.max(maxValueLength, value.toString().length());
        return value;
    };

    public int getMaxKeyLength() {
        return maxKeyLength;
    }

    public int getMaxValueLength() {
        return maxValueLength;
    }
}

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.

rob
  • 6,147
  • 2
  • 37
  • 56
1

I have written a small code that will print the HashMap similar (not exactly) to how query results are printed (like sqlplus). Just sharing here so that it might help some one.

List<Map<String, Object>> resultSet = jdbcTemplate.queryForList(selectQuery);

        Map<String, Integer> maxColSizeMap = new HashMap<String, Integer>();
        boolean initMaxColSizeMap = true;

        for (Map<String, Object> map : resultSet) {

            for (String key : map.keySet()) {
                if (initMaxColSizeMap) {
                    String ColValue = (map.get(key) == null ) ? "" : map.get(key).toString();
                    Integer whoIsBig = Math.max(ColValue.length(), key.length());
                    maxColSizeMap.put(key, whoIsBig);
                } else {
                    String ColValue = (map.get(key) == null ) ? "" : map.get(key).toString();
                    Integer whoIsBig = Math.max(ColValue.length(), key.length());
                    whoIsBig = Math.max(maxColSizeMap.get(key), whoIsBig);
                    maxColSizeMap.put(key, whoIsBig);
                }
            }
            initMaxColSizeMap = false;
        }

        // Column HEADER
        for (Map<String, Object> map : resultSet) {
            System.out.println("");
            StringBuilder colName = new StringBuilder();
            StringBuilder underLine = new StringBuilder();
            for (String key : map.keySet()) {
                colName.append(StringUtils.rightPad(key, maxColSizeMap.get(key)));
                colName.append(" ");

                underLine.append(StringUtils.repeat('-', maxColSizeMap.get(key)));
                underLine.append(" ");
            }
            // Do one time only
            System.out.println(colName.toString());
            System.out.println(underLine.toString());
            break;
        }

        // Print the rows
        for (Map<String, Object> map : resultSet) {
            StringBuilder row = new StringBuilder();
            for (String key : map.keySet()) {
                String str = map.get(key) == null ? "" : map.get(key).toString();
                row.append(StringUtils.rightPad(str, maxColSizeMap.get(key) + 1));
            }
            System.out.println(row);
        }

        System.out.println("");

Note: org.apache.commons.lang3.StringUtils is used for padding.
This one is not an exact answer to the question, so tweak the code as required.

Anver Sadhat
  • 3,074
  • 1
  • 25
  • 26
0

You can use a for-each loop and just print it out, correct? No need to have the size..

Whatever is meant by "table" though?

How print out the contents of a HashMap<String, String> in ascending order based on its values?

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
0

You may want to get all the keys of the map, iterate the keys and print the details e.g.

     Map<String, String> valueMap = new HashMap<String, String>();
     .....
     Set<String> keys = valueMap.keySet();
     Iterator<String> iter = keys.iterator();
     while(iter.haxNext()){
        String key = iter.next();
        System.out.println("\t"+key+"|\t"+valueMap.get(key));
     }

EDIT: If you want specific width then consider using Apache StringUtils as below:

     int MAXWIDTH = 20; //<- set this with the max width of the column
     Map<String, String> valueMap = new HashMap<String, String>();
     .....
     Set<String> keys = valueMap.keySet();
     Iterator<String> iter = keys.iterator();
     while(iter.haxNext()){
        String key = iter.next();
        System.out.println(StringUtils.rightPad(key, MAXWIDTH)+ "|"+
                   StringUtils.rightPad(valueMap.get(key), MAXWIDTH));
     }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73