Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
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
            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;
    }
}