janput
12/5/2016 - 11:09 AM

Output Maps and nested maps to console.Print lists to console

Output Maps and nested maps to console.Print lists to console

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

/**
 * Created by Jan on 5/12/2016.
 */
public class CollectionUtils2 {

    private final static Logger LOGGER = LoggerFactory.getLogger(CollectionUtils2.class);

    private CollectionUtils2() {
    }

    public static void printMap(Map<?, ?> input) {
        LOGGER.info(printMapInternal(input, "\t"));
    }

    public static void printList(Collection c) {
        LOGGER.info(printListInternal(c, "\t"));
    }

    private static String printMapInternal(Map<?, ?> input, String prefix) {
        StringBuilder sb = new StringBuilder();

        if (input == null) {
            sb.append("\n").append(prefix).append("Map is null\n");
        }

        sb.append(input.getClass().getSimpleName()).append("@").append(System.identityHashCode(input));
        if (input.isEmpty()) {
            sb.append(" Map is empty\n");
            return sb.toString();
        }

        sb.append(" containing ").append(input.size()).append(" elements:\n");
        for (Map.Entry<?, ?> entry : input.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            sb.append(prefix).append("[").append(key).append("] = ");

            if (value instanceof Map) {
                sb.append(printMapInternal((Map) value, prefix + "\t"));
            } else if (value instanceof Collection) {
                sb.append(printListInternal((Collection) value, prefix + "\t"));
            } else {
                sb.append(value).append("\n");
            }
        }
        return sb.toString();
    }

    private static String printListInternal(Collection c, String prefix) {
        StringBuilder sb = new StringBuilder();

        if (c == null) {
            sb.append("\n").append(prefix).append("List is null\n");
        }
        sb.append(c.getClass().getSimpleName()).append("@").append(System.identityHashCode(c));
        if (c.isEmpty()) {
            sb.append(" List is empty\n");
            return sb.toString();
        }

        sb.append(" containing ").append(c.size()).append(" elements:\n");
        int i = 0;
        for (Object o : c) {
            sb.append(prefix).append("[").append(i).append("] = ");
            if (o == null) {
                sb.append("null");
            } else if (o.getClass().isArray()) {
                sb.append(printListInternal(Arrays.asList((Object[]) o), prefix + "\t"));
            } else if (o instanceof Collection) {
                sb.append(printListInternal((Collection) o, prefix + "\t"));
            } else {
                sb.append(o.toString());
            }
            sb.append("\n");
            i++;
        }
        return sb.toString();
    }
}