Java Map Sort sortedMap(Map map, Comparator comparator)

Here you can find the source of sortedMap(Map map, Comparator comparator)

Description

Method to sort a map based on the comparator

License

Open Source License

Parameter

Parameter Description
map a parameter
comparator a parameter

Return

Map

Declaration

public static <K, V> Map<K, V> sortedMap(Map<K, V> map, Comparator<K> comparator) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from w  w  w .jav a2  s.  c  o m
     * Method to sort a map based on the comparator
     * 
     * @param map
     * @param comparator
     * @return {@link Map<K, V>}
     */
    public static <K, V> Map<K, V> sortedMap(Map<K, V> map, Comparator<K> comparator) {
        if (map != null && comparator != null) {
            Map<K, V> returnValue = new HashMap<>();
            List<K> list = new ArrayList<>();
            for (K key : map.keySet()) {
                list.add(key);
            }
            Collections.sort(list, comparator);
            for (int i = 0; i < list.size(); i++) {
                K key = list.get(i);
                returnValue.put(key, map.get(key));
            }
            return returnValue;
        }
        return null;
    }
}

Related

  1. sortByValuesDesc(final Map map)
  2. sortClustersKeys(final Map> clusters)
  3. sortDoubleMap(Map map)
  4. sortedByRankThenLength(Map map)
  5. sortedKeys(Map map)
  6. sortedString(Map c)
  7. sortedString(Map c)
  8. sortedTable(Map map)
  9. sortedView(Map original, int numItems)