java8 Map转String工具类

public class MapToStringUtil {
    /**
     * Map转String工具
     * @param map
     * @param separator 分隔符
     * @param kvSplice  键值拼接符
     * @return
     */
    public static String mapToString(Map map, String separator, String kvSplice) {
        List result = new ArrayList<>();
        map.entrySet().parallelStream().reduce(result, (first, second)->{
            first.add(second.getKey() + kvSplice + second.getValue());
            return first;
        }, (first, second)->{
            if (first == second) {
                return first;
            }
            first.addAll(second);
            return first;
        });

        return StringUtils.join(result, separator);
    }

    public static void main(String[] args) {
        Map map = Maps.newHashMap();
        map.put("name", "hjz");
        map.put("value", 25);

        System.out.println(MapToStringUtil.mapToString(map, ";", ":"));
        //name:hjz;value:25
    }
}

 

你可能感兴趣的:(java)