集册 Java实例教程 将Map<String,Object>转换为字符串

将Map<String,Object>转换为字符串

欢马劈雪     最近更新时间:2020-01-02 10:19:05

605
将Map<String,Object>转换为字符串
//时 代      J a v a   公   众 号 - nowjava.com 提 供

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);

            }

        }
        /*
        时   代     Java  公  众  号 - nowjava.com
        */

        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(
展开阅读全文