---
title: "map 排序"
author: "yrandy"
date: "2012-09-28T10:44:19Z"
tags: []
categories: ["移动开发"]
slug: "map"
draft: false
lastmod: "2012-09-28T10:47:30Z"
id: 1687787
url: "https://yrandy.iteye.com/blog/1687787"
---

**用于map的值排序的方法，修改SortedSet 的方法即可，代码见下方：**

public class MapHandle {

//重写compare方法

static &lt;K, V extends Comparable&lt;? super V&gt;&gt; SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; entriesSortedByValues(Map&lt;K, V&gt; map) {

SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; sortedEntries = new TreeSet&lt;Map.Entry&lt;K, V&gt;&gt;(

new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {

@Override

public int compare(Map.Entry&lt;K, V&gt; e1, Map.Entry&lt;K, V&gt; e2) {

int res = e2.getValue().compareTo(e1.getValue());  //key排序，调换e2与e1的位置即可

return res != 0 ? res : 1; // Special fix to preserve

// items with equal values

}

});

sortedEntries.addAll(map.entrySet());

return sortedEntries;

}

public static void main(String\[] args) {

Map&lt;String, Integer&gt; map = new TreeMap&lt;String, Integer&gt;();

map.put("苹果", 2);

map.put("梨子", 1);

map.put("香蕉", 3);

map.put("橘子", 3);

map.put("菠萝", 3);

map.put("西瓜", 3);

map.put("桃子", 3);

for (String string : map.keySet()) {

System.out.print(string + ":");

System.out.println(map.get(string));

}

System.out.println(map);    //原本的输出结果

System.out.println(entriesSortedByValues(map));    //调用后的结果

}

}

 

输出结果：

桃子:3

梨子:1

橘子:3

苹果:2

菠萝:3

西瓜:3

香蕉:3

{桃子=3, 梨子=1, 橘子=3, 苹果=2, 菠萝=3, 西瓜=3, 香蕉=3}

\[桃子=3, 橘子=3, 菠萝=3, 西瓜=3, 香蕉=3, 苹果=2, 梨子=1]