本帖最后由 被淹死的虫子 于 2015-5-30 14:43 编辑
度娘上总结了两种思路,大婶们还有木有更先进的?
- <p>public class TreeMapDemo {</p><p> public static void main(String[] args) {
- Map<String, String> map = new TreeMap<String, String>();
- map.put("zhangsan", "上海");
- map.put("lisisi", "北京");
- map.put("wanger", "上海");
- map.put("aliang", "深圳");
- map.put("liuda", "上海");
- map.put("sunqi", "北京");
- System.out.println(map);</p><p> //方式一
- List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(
- map.entrySet());
- Collections.sort(list, new Comparator<Map.Entry<String, String>>() {</p><p> public int compare(Entry<String, String> o1,
- Entry<String, String> o2) {
- return o1.getValue().compareTo(o2.getValue());
- }
- });
- System.out.println(list);
-
- //方式二
- Map<String, String> map1 = new TreeMap<String, String>(
- new Comparator<String>() {
- public int compare(String o1, String o2) {
- int temp = map.get(o1).compareTo(map.get(o2));
- return temp == 0 ? 1 : temp;
- }
- });
- map1.putAll(map);
- System.out.println(map1);
- }
- }
- </p><p> </p>
复制代码
捣鼓了一早上。。。。发觉这个Comparator简直是神器啊!!!
|