一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - 淺談Java之Map 按值排序 (Map sort by value)

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

2020-06-04 11:58jingxian JAVA教程

下面小編就為大家?guī)硪黄獪\談Java之Map 按值排序 (Map sort by value)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

Map是鍵值對的集合,又叫作字典或關(guān)聯(lián)數(shù)組等,是最常見的數(shù)據(jù)結(jié)構(gòu)之一。在java如何讓一個map按value排序呢? 看似簡單,但卻不容易!

比如,Map中key是String類型,表示一個單詞,而value是int型,表示該單詞出現(xiàn)的次數(shù),現(xiàn)在我們想要按照單詞出現(xiàn)的次數(shù)來排序:

?
1
2
3
4
5
6
7
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);

按值排序的結(jié)果應(yīng)該是:

?
1
2
3
4
5
6
7
key value
me 1000
you 3000
and 4000
hungry 5000
later 6000
food 10000

首先,不能采用SortedMap結(jié)構(gòu),因為SortedMap是按鍵排序的Map,而不是按值排序的Map,我們要的是按值排序的Map。

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

方法一:

如下Java代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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++代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);

上面方法的實質(zhì)意義是:將Map結(jié)構(gòu)中的鍵值對(Map.Entry)封裝成一個自定義的類(結(jié)構(gòu)),或者直接用Map.Entry類。自定義類知道自己應(yīng)該如何排序,也就是按值排序,具體為自己實現(xiàn)Comparable接口或構(gòu)造一個Comparator對象,然后不用Map結(jié)構(gòu)而采用有序集合(SortedSet, TreeSet是SortedSet的一種實現(xiàn)),這樣就實現(xiàn)了Map中sort by value要達(dá)到的目的。就是說,不用Map,而是把Map.Entry當(dāng)作一個對象,這樣問題變?yōu)閷崿F(xiàn)一個該對象的有序集合或?qū)υ搶ο蟮募献雠判颉<瓤梢杂?/span>SortedSet,這樣插入完成后自然就是有序的了,又或者用一個List或數(shù)組,然后再對其做排序(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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 中實現(xiàn) sort map by value,當(dāng)然本質(zhì)是一樣的,但卻很簡潔 : 

用 groovy 中 map 的 sort 方法(需要 groovy 1.6),

?
1
2
3
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 }

結(jié)果為: [b:1, d:2, a:3, c:4]

Python中也類似:

 

?
1
2
3
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)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 丝袜白浆 | 久久99视热频国只有精品 | 国产欧美另类 | 疯狂伦交1一6 小说 风间由美在线 | 999精品视频在线 | 亚洲精品短视频 | 手机看片福利盒子久久 | 亚洲精选在线观看 | 国产一区二区三区水野朝阳 | 免费的毛片视频 | 成人精品一区二区三区中文字幕 | 好大好硬好深好爽想要小雪 | 日韩精品免费一级视频 | 国人精品视频在线观看 | 亚洲精品久久久打桩机 | 5x社区在线观看直接进入 | 国产精品 视频一区 二区三区 | 久久成人伊人欧洲精品AV | 不卡一区二区三区卡 | 美女的隐私视频免费看软件 | 特黄a大片免费视频 | 惩罚美女妲己的尤老师 | 被老外操 | 国产欧美成人免费观看 | 非洲一级毛片又粗又长aaaa | 亚洲欧美在线免费观看 | 国产一区二区三区高清 | 亚洲国产欧美目韩成人综合 | 日韩精品在线一区二区 | 男人午夜免费视频 | 69av导航 | 91丝袜足控免费网站xx | 日本中文字幕二区三区 | 日韩一级片在线免费观看 | 亚洲天堂日韩在线 | jizz农村野外jizz农民 | 亚洲欧美天堂 | 草逼视频免费看 | 四虎影视地址 | 日本一卡2卡3卡4卡乱 | 国产一区二区精品 |