程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 淺談Java之Map 按值排序 (Map sort by value)

淺談Java之Map 按值排序 (Map sort by value)

編輯:關於JAVA

淺談Java之Map 按值排序 (Map sort by value)。本站提示廣大學習愛好者:(淺談Java之Map 按值排序 (Map sort by value))文章只能為提供參考,不一定能成為您想要的結果。以下是淺談Java之Map 按值排序 (Map sort by value)正文


Map是鍵值對的聚集,又叫作字典或聯系關系數組等,是最多見的數據構造之一。在java若何讓一個map按value排序呢? 看似簡略,但卻不輕易!

好比,Map中key是String類型,表現一個單詞,而value是int型,表現該單詞湧現的次數,如今我們想要依照單詞湧現的次數來排序:

Map map = new TreeMap();
map.put("me", 1000);
map.put("and", 4000);
map.put("you", 3000);
map.put("food", 10000);
map.put("hungry", 5000);
map.put("later", 6000);

按值排序的成果應當是:

key value
me 1000
you 3000
and 4000
hungry 5000
later 6000
food 10000

起首,不克不及采取SortedMap構造,由於SortedMap是按鍵排序的Map,而不是按值排序的Map,我們要的是按值排序的Map。

Couldn't you do this with a SortedMap? 
No, because the map are being sorted by its keys.

辦法一:

以下Java代碼:

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {

    Set set = new TreeSet();
    set.add(new Pair("me", "1000"));

    set.add(new Pair("and", "4000"));
    set.add(new Pair("you", "3000"));

    set.add(new Pair("food", "10000"));
    set.add(new Pair("hungry", "5000"));

    set.add(new Pair("later", "6000"));
    set.add(new Pair("myself", "1000"));

    for (Iterator i = set.iterator(); i.hasNext();)

      System.out.println(i.next());
  }
}

class Pair implements Comparable {
  private final String name;
  private final int number;

  public Pair(String name, int number) {
    this.name = name;
    this.number = number;
  }

  public Pair(String name, String number) throws NumberFormatException {
    this.name = name;
    this.number = Integer.parseInt(number);

  }

  public int compareTo(Object o) {
    if (o instanceof Pair) {
      int cmp = Double.compare(number, ((Pair) o).number);
      if (cmp != 0) {
        return cmp;
      }
      return name.compareTo(((Pair) o).name);
    }

    throw new ClassCastException("Cannot compare Pair with "
        + o.getClass().getName());

  }

  public String toString() {
    return name + ' ' + number;
  }
}

相似的C++代碼:

typedef pair<string, int> PAIR;

int cmp(const PAIR& x, const PAIR& y)
{
  return x.second > y.second;
}

map<string,int> m;
vector<PAIR> vec;
for (map<wstring,int>::iterator curr = m.begin(); curr != m.end(); ++curr)
{
  vec.push_back(make_pair(curr->first, curr->second));
}
sort(vec.begin(), vec.end(), cmp);

下面辦法的本質意義是:將Map構造中的鍵值對(Map.Entry)封裝成一個自界說的類(構造),或許直接用Map.Entry類。自界說類曉得本身應當若何排序,也就是按值排序,詳細為本身完成Comparable接口或結構一個Comparator對象,然後不消Map構造而采取有序聚集(SortedSet, TreeSet是SortedSet的一種完成),如許就完成了Map中sort by value要到達的目標。就是說,不消Map,而是把Map.Entry看成一個對象,如許成績變成完成一個該對象的有序聚集或對該對象的聚集做排序。既可以用SortedSet,如許拔出完成後天然就是有序的了,又或許用一個List或數組,然後再對其做排序(Collections.sort() or Arrays.sort())。

Encapsulate the information in its own class. Either implement
Comparable and write rules for the natural ordering or write a
Comparator based on your criteria. Store the information in a sorted
collection, or use the Collections.sort() method.

辦法二:

You can also use the following code to sort by value:

public static Map sortByValue(Map map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {

      public int compare(Object o1, Object o2) {
        return ((Comparable) ((Map.Entry) (o1)).getValue())
            .compareTo(((Map.Entry) (o2)).getValue());

      }
    });
    Map result = new LinkedHashMap();

    for (Iterator it = list.iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entry) it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }

  public static Map sortByValue(Map map, final boolean reverse) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {

      public int compare(Object o1, Object o2) {
        if (reverse) {
          return -((Comparable) ((Map.Entry) (o1)).getValue())
              .compareTo(((Map.Entry) (o2)).getValue());
        }
        return ((Comparable) ((Map.Entry) (o1)).getValue())
            .compareTo(((Map.Entry) (o2)).getValue());
      }
    });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entry) it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    return result;
  }




        Map map = new HashMap();
    map.put("a", 4);
    map.put("b", 1);
    map.put("c", 3);
    map.put("d", 2);
    Map sorted = sortByValue(map);
    System.out.println(sorted);
// output : {b=1, d=2, c=3, a=4}

或許還可以如許:
Map map = new HashMap();
    map.put("a", 4);
    map.put("b", 1);
    map.put("c", 3);
    map.put("d", 2);

    Set<Map.Entry<String, Integer>> treeSet = new TreeSet<Map.Entry<String, Integer>>(
        new Comparator<Map.Entry<String, Integer>>() {
          public int compare(Map.Entry<String, Integer> o1,
              Map.Entry<String, Integer> o2) {
            Integer d1 = o1.getValue();
            Integer d2 = o2.getValue();
            int r = d2.compareTo(d1);

            if (r != 0)
              return r;
            else
              return o2.getKey().compareTo(o1.getKey());
          }

        });
    treeSet.addAll(map.entrySet());
    System.out.println(treeSet);
    // output : [a=4, c=3, d=2, b=1]

別的,Groovy 中完成 sort map by value,固然實質是一樣的,但卻很簡練 : 

用 groovy 中 map 的 sort 辦法(須要 groovy 1.6),

def result = map.sort(){ a, b -> 
      b.value.compareTo(a.value)
    }

如:

 ["a":3,"b":1,"c":4,"d":2].sort{ a,b -> a.value - b.value }

成果為: [b:1, d:2, a:3, c:4]

Python中也相似:

 

h = {"a":2,"b":1,"c":3}
i = h.items() // i = [('a', 2), ('c', 3), ('b', 1)]
i.sort(lambda (k1,v1),(k2,v2): cmp(v2,v1) ) // i = [('c', 3), ('a', 2), ('b', 1)]

以上這篇淺談Java之Map 按值排序 (Map sort by value)就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved