web-dev-qa-db-ja.com

値に基づいて降順でMap <Key、Value>をソートする

可能性のある複製:
Javaの値でMap <Key、Value>をソートする方法?

マップインターフェイスを使用して、ファイルから読み取り、その中に値をキーと値のペアとして保存します。ファイル形式は次のとおりです

 A 34
 B 25
 c 50

このファイルからデータを読み取り、キーと値のペアとして保存し、ユーザーに表示します。私の要件は、この形式で結果を表示することです

C 50
A 34
B 25

したがって、値の降順でマップをソートする必要があります。結果としてこれらを表示できるように..これについて読み、以下のコードを見つけました

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

これが昇順で値を並べ替えることを願っていますが、このアプローチが正しいかどうか、または他の効果的なアプローチが私にとって役立つかどうかを知りたいですか?

29
NandaKumar

値が重複する可能性があるため、Setを使用しないでください。 Listに変更して、代わりに並べ替えます。 entriesSortedByValuesは次のようになります。

_static <K,V extends Comparable<? super V>> 
            List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {

    List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());

    Collections.sort(sortedEntries, 
            new Comparator<Entry<K,V>>() {
                @Override
                public int compare(Entry<K,V> e1, Entry<K,V> e2) {
                    return e2.getValue().compareTo(e1.getValue());
                }
            }
    );

    return sortedEntries;
}
_

注:出力例では、値は降順です。昇順が必要な場合は、代わりにe1.getValue().compareTo(e2.getValue())を使用してください。


例:

_public static void main(String args[]) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 34);
    map.put("B", 25);
    map.put("C", 50);
    map.put("D", 50); // "duplicate" value

    System.out.println(entriesSortedByValues(map));
}
_

出力:

_[D=50, C=50, A=34, B=25]
_
48
dacwe

独自のcomparatorを作成してTreeMapに渡します

class MyComparator implements Comparator {

Map map;

public MyComparator(Map map) {
    this.map = map;
}

public int compare(Object o1, Object o2) {

    return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));

}
}

テストクラスで

Map<String, Integer> lMap=new HashMap<String, Integer>();
    lMap.put("A", 35);
    lMap.put("B", 25);
    lMap.put("C", 50);

    MyComparator comp=new MyComparator(lMap);

    Map<String,Integer> newMap = new TreeMap(comp);
    newMap.putAll(lMap);

OutPut:

C=50
A=35
B=25
13
amicngh