convert Map<String, Object> To String - Java Collection Framework

Java examples for Collection Framework:Map

Description

convert Map<String, Object> To String

Demo Code

public class Main{

    public static String convertToString(
            java.util.Map<String, Object> properties) {
        java.util.List<String> parts = new java.util.ArrayList<String>();
        for (String key : properties.keySet()) {
            Object value = properties.get(key);
            if (value instanceof String) {
                parts.add(encode('=', new String[] { key, (String) value }));
            } else {
                throw new RuntimeException("Can't encode " + value);
            }// ww  w  . j a  v a 2s.  c om
        }
        return encode(';', parts);
    }
    public static String encode(char delimiter, String[] parts) {
        java.util.List<String> partList = new java.util.ArrayList<String>();
        for (String part : parts) {
            partList.add(part);
        }
        return encode(delimiter, partList);
    }
    public static String encode(char delimiter, Iterable<String> parts) {
        StringBuilder result = new StringBuilder();
        for (String part : parts) {
            String encodedPart = part.replace("\\", "\\\\");
            encodedPart = encodedPart.replace("" + delimiter, "\\"
                    + delimiter);
            result.append(encodedPart);
            result.append(delimiter);
        }
        return result.toString();
    }

}

Related Tutorials