Java: pretty print data structures

Java lacks functionality to pretty print data structures. Let’s remedy that situation.

To make that work we will use code from some other posts : [Is scalar], [join], [List to Map].

It is simple recursive function : dump()

Below you can see an example usage.

You can also experiment with the code here.

import java.util.*;
import java.util.Map.Entry;

class Dump {
  
  	//the biggest invention in Java-world since sliced-bread ;)
	public static <ARG> void say(ARG arg) { System.out.println(arg); }

        //joins Iterable or Collection into a String
	public static <T> String join(String delimiter, Iterable<T> lst) {
		StringBuilder str = new StringBuilder();
		Iterator<T> it = lst.iterator();
		while ( it.hasNext() ) {
			str.append(it.next().toString());
			if (it.hasNext()) str.append(delimiter);
		}
		return str.toString();
	}

  	//for Classes check if the value is SCALAR
	public static boolean is_scalar(Object var) {
	    if( (var instanceof Number) || (var instanceof String) || (var instanceof Boolean)) return true;
	    return false;
	}


	public static HashMap<Integer, ?> list2map(List lst) {
		HashMap map = new HashMap();
		for (int i=0; i < lst.size(); i++) {
			map.put(i, lst.get(i));
		}
		return map;
	}	
	
	public static String dump(List lst, String... offset) {
		return dump(list2map(lst), offset);
	}
	
	// Pretty print a LoL structure, for debugging purposes
	public static String dump(Map m, String... offset) {
		if (m == null) return "";
	    StringBuilder rv = new StringBuilder();
	    String delta = offset.length == 0 ? "" : offset[0];
	    for( Entry e : (Set<Map.Entry>) m.entrySet() ) {
	        rv.append( delta + e.getKey() + " : " );
	        Object value = e.getValue();
	        if( value instanceof Map ) rv.append( ">\n" + dump((Map) value, delta + "  ") ); 
	        if( value instanceof Collection ) rv.append( "[" + join(",", (Collection) value) + "]\n" );
	        if( is_scalar(value) ) rv.append( value +"\n" );
	    } 
	    return rv.toString();
	}
	
	public static void main(String[] args) {
		  
      List lst = Arrays.asList(1,2,3,4);
      HashMap lvl2 = new HashMap() {{
       put("key2-1", "value2-1");
       put("key2-2", "value2-2");
      }};
      
      
      HashMap map = new HashMap() {{
       put("key", "value");
       put("lvl2", lvl2);
       put("lst",lst);
      }};
      
      
      say(dump(map));
	}
	
}	

here is the output :

lvl2 : >
  key2-2 : value2-2
  key2-1 : value2-1
lst : [1,2,3,4]
key : value