Java Map Sort sortKeyValuePairByValue( Map map)

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

Description

Utility method to sort the keys and values of a map by their value.

License

Open Source License

Declaration

public static <K extends Comparable<? super K>, V extends Comparable<? super V>> List<Entry<K, V>> sortKeyValuePairByValue(
        Map<K, V> map) 

Method Source Code

//package com.java2s;
/* This file is part of VoltDB.
 * Copyright (C) 2008-2015 VoltDB Inc./*from  w  w w  . j  av a2s. c  o m*/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;

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

public class Main {
    /**
     * Utility method to sort the keys and values of a map by their value.
     */
    public static <K extends Comparable<? super K>, V extends Comparable<? super V>> List<Entry<K, V>> sortKeyValuePairByValue(
            Map<K, V> map) {
        List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                if (!o1.getValue().equals(o2.getValue())) {
                    return (o1.getValue()).compareTo(o2.getValue());
                }
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        return entries;
    }
}

Related

  1. sortEntries(Map map, Comparator> comparator)
  2. sortHashMapByValuesD(HashMap passedMap)
  3. sortingHelperSessions(String column, Map sortParams)
  4. sortKeysByValue(final Map m)
  5. sortKeysDesc(HashMap> hash)
  6. sortMap(final Map map, final Comparator> comparator)
  7. sortMap(LinkedHashMap map, Comparator> c)
  8. sortMap(Map oldMap)
  9. sortMap(Map oldMap, final boolean asc)