package com.capgemini.framework.common;

import java.util.*;

/**
 * Utility class for Maps.
 **/
public final class MapHelper {

    /**
     * Constructor.
     **/
    private MapHelper() {
        // Constructor of helper classes must be private
    }

    /**
     * String displaying of a Map.
     *
     * @param aMap Map which should be displayed
     * @return String representation of the map
     **/
    public static String toString(final Map<String, ?> aMap) {

        StringBuilder theStringBuilder = new StringBuilder();

        // Get map key values and sort them 
        Set<String> theKeySet = aMap.keySet();
        List<String> theSortedSet = sortSet(theKeySet);

        // Browse sorted values 
        for (String currentKey : theSortedSet) {
            theStringBuilder.append(currentKey).append('=').append(aMap.get(currentKey)).append(StringHelper.LINE_FEED);
        }

        return theStringBuilder.toString();
    }

    /**
     * Sort a set of strings.
     *
     * @param aValuesSet Set to sort
     * @return sorted list
     */
    private static List<String> sortSet(final Set<String> aValuesSet) {

        String[] stArray = aValuesSet.toArray(new String[aValuesSet.size()]);

        // Convert array of elements to sort to a list 
        List<String> sortedList = Arrays.asList(stArray);

        Collections.sort(sortedList);
        return sortedList;
    }
}
