sort Map By Value Desc - Android java.util

Android examples for java.util:Map

Description

sort Map By Value Desc

Demo Code


//package com.book2s;
import java.util.AbstractMap.SimpleEntry;

import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
    public static <K, V extends Comparable<? super V>> SortedSet<Entry<K, V>> sortMapByValueDesc(
            Map<K, V> map) {
        SortedSet<Entry<K, V>> sorted = new TreeSet<>(
                new Comparator<Entry<K, V>>() {
                    @Override//from  w w w.  ja  v  a2  s . co m
                    public int compare(Entry<K, V> e1, Entry<K, V> e2) {
                        int r = e2.getValue().compareTo(e1.getValue());
                        return r == 0 ? 1 : r;
                    }
                });

        for (Entry<K, V> entry : map.entrySet())
            sorted.add(new SimpleEntry(entry));
        return sorted;
    }
}

Related Tutorials