Pacific-Design.com

    
Home Index

1. Algorithms

2. Pretty Map

Algorithms / Pretty Map /

Java Template to print key/value pair

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/*---------------------------------------------------------------------
      Usage: System.out.println(new PrettyMap<>(map));
*/

public class PrettyMap<K, V> {
    
    private final Map<K, V> map;
    
    /*---------------------------------------------------------------*/
    public PrettyMap(Map<K, V> map) {
        this.map = map;
    }

    /*---------------------------------------------------------------*/
    @Override
    public String toString() {
        
        StringBuilder sb = new StringBuilder();
        Iterator<Entry<K, V>> iter = map.entrySet().iterator();
        
        sb.append("{\n");
        while (iter.hasNext()) {
            
            Entry<K, V> entry = iter.next();
            sb.append("  ").append(entry.getKey());
            sb.append(" = ").append('"');
            sb.append(entry.getValue());
            sb.append('"');
            
            if (iter.hasNext()) {
                sb.append(',').append('\n');
            }
        }
        sb.append("\n}\n");
        return sb.toString();
    }
    /*---------------------------------------------------------------*/
}