Java Map Sort sortMapByValue(Map map, Comparator comparator)

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

Description

Sort a Map by value and save it as a linkedHashMap to ensure the order is kept.

License

Apache License

Parameter

Parameter Description
K a parameter
V a parameter
map a parameter
comparator a parameter

Declaration

public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map,
        Comparator comparator) 

Method Source Code


//package com.java2s;
/*//from   w w  w.j  a  va  2  s.  c  o  m
 * Copyright 2014 hector.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * Sort a Map by value and save it as a linkedHashMap to ensure the order is
     * kept. You need to provide the map and the comparator so that you can use
     * this function to get different types of orderings by value (ascending,
     * descending, ...)
     * 
     * @param <K>
     * @param <V>
     * @param map
     * @param comparator
     * @return 
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map,
            Comparator comparator) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, comparator);

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Related

  1. sortMap(Map map, int k)
  2. sortMap(Map map, Comparator> compator)
  3. sortMapByKey(Map data)
  4. sortMapByKey(Map map)
  5. sortMapByValue(Map input, final boolean desc)
  6. sortMapByValue(Map map, Comparator> valueComparator)
  7. sortMapByValue(Map map, Comparator> comparator)
  8. sortMapByValue(Map map, final boolean descending)
  9. sortMapByValue(Map oriMap)