All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.twilio.converter.PrefixedCollapsibleMap Maven / Gradle / Ivy

There is a newer version: 10.1.5
Show newest version
package com.twilio.converter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrefixedCollapsibleMap {

    private static Map flatten(
        Map map,
        Map result,
        List previous
    ) {
        for (Map.Entry entry : map.entrySet()) {
            List next = new ArrayList<>(previous);
            next.add(entry.getKey());

            if (entry.getValue() instanceof Map) {
                flatten((Map) entry.getValue(), result, next);
            } else {
                result.put(String.join(".", next), entry.getValue().toString());
            }
        }

        return result;
    }

    /**
     * Flatten a Map of String, Object into a Map of String, String where keys are '.' separated
     * and prepends a key.
     *
     * @param map    map to transform
     * @param prefix key to prepend
     * @return flattened map
     */
    public static Map serialize(Map map, String prefix) {
        if (map == null || map.isEmpty()) {
            return Collections.emptyMap();
        }

        Map flattened = flatten(map, new HashMap(), new ArrayList());

        Map result = new HashMap<>();
        for (Map.Entry entry : flattened.entrySet()) {
            result.put(prefix + "." + entry.getKey(), entry.getValue());
        }

        return result;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy