Java Map to String mapToString(Map map)

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

Description

map To String

License

Open Source License

Declaration

public static String mapToString(Map<String, Object> map) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    public static String mapToString(Map<String, Object> map) {
        LinkedList<String> pairs = new LinkedList<String>();
        ArrayList<String> keyList = new ArrayList<String>(map.keySet());
        Collections.sort(keyList);
        for (String s : keyList) {
            Object value = map.get(s);
            String valueStr = toString(value);
            pairs.add(s + ": " + valueStr);
        }/*from www .j ava  2  s  . c  o  m*/

        return "{" + join(", ", pairs.toArray()) + "}";
    }

    @SuppressWarnings("unchecked")
    public static String toString(Object value) {
        if (value instanceof Map)
            return mapToString((Map<String, Object>) value);
        else if (value instanceof List)
            return listToString((List<Object>) value);
        else if (value == null)
            return "null";
        else
            return value.toString().trim();
    }

    public static String join(Object[] tokens, String delimiter) {
        if (tokens.length == 0)
            return "";

        StringBuilder joined = new StringBuilder();

        boolean first = true;
        for (Object token : tokens) {
            if (!first)
                joined.append(delimiter);
            else
                first = false;
            joined.append(token);
        }

        return joined.toString();
    }

    public static String join(String delimiter, Object... tokens) {
        return join(tokens, delimiter);
    }

    public static String listToString(List<Object> value) {
        Object[] valueStrings = new Object[value.size()];
        for (int i = 0; i < valueStrings.length; i++) {
            valueStrings[i] = toString(value.get(i));
        }
        return "[" + join(", ", valueStrings) + "]";
    }
}

Related

  1. mapToString(Map map)
  2. mapToString(Map map)
  3. mapToString(Map map)
  4. mapToString(Map acs)
  5. mapToString(Map m)
  6. mapToString(Map criteria)
  7. MapToString(Map map)
  8. mapToString(Map map)
  9. mapToString(Map map)