Java Map to String toString(Map map)

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

Description

Returns a String showing the type and first few elements of a map

License

Apache License

Declaration

public static <A, B> String toString(Map<A, B> map) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.util.Map;

public class Main {
    /** Returns a String showing the type and first few elements of a map */
    public static <A, B> String toString(Map<A, B> map) {
        if (map == null) {
            return "null";
        }/*from w w w  .  j av a2  s . c o m*/
        StringBuilder sB = new StringBuilder();

        sB.append(map.getClass().getSimpleName());
        sB.append("(");

        int i = 0;
        for (Map.Entry<A, B> item : map.entrySet()) {
            if (i > 4) {
                sB.append(",...");
                break;
            } else if (i > 0) {
                sB.append(",");
            }
            sB.append("Entry(").append(String.valueOf(item.getKey())).append(",");
            sB.append(String.valueOf(item.getValue())).append(")");
            i++;
        }

        sB.append(")");
        return sB.toString();
    }

    /** Returns a String showing the type and first few elements of an array */
    public static String toString(Object[] as) {
        if (as == null) {
            return "null";
        }
        StringBuilder sB = new StringBuilder();
        sB.append("Array");

        if ((as.length > 0) && (as[0] != null)) {
            sB.append("<");
            sB.append(as[0].getClass().getSimpleName());
            sB.append(">");
        }

        sB.append("(");

        int i = 0;
        for (Object item : as) {
            if (i > 4) {
                sB.append(",...");
                break;
            } else if (i > 0) {
                sB.append(",");
            }
            sB.append(String.valueOf(item));
            i++;
        }

        sB.append(")");
        return sB.toString();
    }
}

Related

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