Java Map Sort sortByValues(Map map)

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

Description

Returns a list of entries sorted by the values descending.

License

Open Source License

Parameter

Parameter Description
map a parameter

Declaration

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

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.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    /**//  www .j  ava 2s . c  o  m
     * Returns a list of entries sorted by the values descending.
     * @param map
     * @return
     */
    public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValues(Map<K, V> map) {
        return sortByValues(map, false);
    }

    /**
     * Returns a list of entries sorted by the values either ascending or descending.
     * @param map
     * @return
     */
    public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValues(Map<K, V> map,
            final boolean ascending) {
        List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());
        Collections.sort(entries, new Comparator<Entry<K, V>>() {

            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                if (ascending) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });
        return entries;
    }
}

Related

  1. sortByValueDESC(Map map)
  2. sortByValueDescending( Map map)
  3. sortByValues( Map map)
  4. sortByValues(final Map map)
  5. sortByValues(Map map, final Comparator comp)
  6. sortByValues(Map map)
  7. sortByValues(Map map)
  8. sortByValues(Map map)
  9. sortByValuesDesc(final Map map)