Java Map Sort sortByValues(Map map)

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

Description

sort map entries by value an return them in a sorted list

License

Open Source License

Parameter

Parameter Description
map a parameter

Declaration

public static <K, V extends Comparable> List<Entry<K, V>> sortByValues(Map<K, V> map) 

Method Source Code


//package com.java2s;
/*// w w w . j a  va 2 s . c  o  m
 * TacTex - a power trading agent that competed in the Power Trading Agent Competition (Power TAC) www.powertac.org
 * Copyright (c) 2013-2016 Daniel Urieli and Peter Stone {urieli,pstone}@cs.utexas.edu               
 *
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This file 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  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 {
    /**
     * sort map entries by value an return them in a sorted list
     * @param map
     * @return
     */
    public static <K, V extends Comparable> List<Entry<K, V>> sortByValues(Map<K, V> map) {
        // create an array from the entries
        List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.entrySet());
        // sort entries by value, assuming value is Comparable
        Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return entries;
    }
}

Related

  1. sortByValues( Map map)
  2. sortByValues(final Map map)
  3. sortByValues(Map map, final Comparator comp)
  4. sortByValues(Map map)
  5. sortByValues(Map map)
  6. sortByValues(Map map)
  7. sortByValuesDesc(final Map map)
  8. sortClustersKeys(final Map> clusters)
  9. sortDoubleMap(Map map)