Java Map Sort toSortedString(Map map)

Here you can find the source of toSortedString(Map map)

Description

Converts the given Map into a String in which the entries of the map are sorted by key + "=" + value pairs.

License

Open Source License

Parameter

Parameter Description
map The Map to convert into a sorted String .

Return

The which shows the sorted map elements or null if the given map was null .

Declaration

public static String toSortedString(Map<?, ?> map) 

Method Source Code

//package com.java2s;
// Public License. See LICENSE.TXT for details.

import java.util.Collections;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    /**//from w w  w . ja va 2  s  .com
     * Converts the given {@link Map} into a {@link String} in which
     * the entries of the map are sorted by {@code key + "=" + value} pairs.
     * @param map The {@link Map} to convert into a sorted {@link String}.
     * @return The {@link String} which shows the sorted map elements or {@code null} if the given map was {@code null}.
     */
    public static String toSortedString(Map<?, ?> map) {
        if (map != null) {
            // Sort entries
            List<String> entries = new LinkedList<String>();
            for (Entry<?, ?> entry : map.entrySet()) {
                entries.add(entry.getKey() + "=" + entry.getValue());
            }
            Collections.sort(entries);
            // Create result
            StringBuffer sb = new StringBuffer();
            sb.append('{');
            boolean afterFirst = false;
            for (String entry : entries) {
                if (afterFirst) {
                    sb.append(", ");
                } else {
                    afterFirst = true;
                }
                sb.append(entry);
            }
            sb.append('}');
            return sb.toString();
        } else {
            return null;
        }
    }
}

Related

  1. sortMapUsingComparator(final Map map, final Comparator comparator)
  2. sortParams(Map params)
  3. sortSimilarityMapByValue(SortedMap temp)
  4. sortValue(Map toSort, boolean descending, final boolean thenByKey)
  5. sortXLabels(Map xLabels)