Java Map to String toString(Map map)

Here you can find the source of toString(Map map)

Description

to String

License

Apache License

Declaration

public static <K, V> String toString(Map<K, V> map) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Map;

public class Main {
    public static <K, V> String toString(Map<K, V> map) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        boolean first = true;
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (first) {
                first = false;/*  w w w  .  j a  va2 s .c  om*/
            } else {
                sb.append(",");
            }
            sb.append(" ");
            if (entry.getKey() == map || entry.getValue() == map) {
                // don't overflow stack if map contains itself
                safeToString(sb, entry.getKey(), entry, "( this entry )", map, "( this map )");
                sb.append(" => ");
                safeToString(sb, entry.getValue(), entry, "( this entry )", map, "( this map )");
            } else {
                sb.append(entry);
            }
        }
        sb.append(" ]");
        return sb.toString();
    }

    public static String toString(Map.Entry<?, ?> entry) {
        StringBuilder sb = new StringBuilder();
        safeToString(sb, entry.getKey(), entry, "( this entry )");
        sb.append(" => ");
        safeToString(sb, entry.getValue(), entry, "( this entry )");
        return sb.toString();
    }

    private static void safeToString(StringBuilder sb, Object o, Object current1, String substitute1,
            Object current2, String substitute2) {
        if (o == current1) {
            sb.append(substitute1);
        } else if (o == current2) {
            sb.append(substitute2);
        } else {
            sb.append(o);
        }
    }

    private static void safeToString(StringBuilder sb, Object o, Object current, String substitute) {
        if (o == current) {
            sb.append(substitute);
        } else {
            sb.append(o);
        }
    }
}

Related

  1. toString(Map map)
  2. toString(Map map)
  3. toString(Map m)
  4. toString(Map map)
  5. toString(Map map)
  6. toString(Map map)
  7. toString(Map m)
  8. toString(Map map)
  9. toString(Map map)