读书人

对地图,hasttable的value进行排序

发布时间: 2012-08-28 12:37:01 作者: rapoo

对map,hasttable的value进行排序

大家可能经常会遇到需要对map,hashtalbe进行排序的需求,并且会为此头疼。不多说,直接上代码:

package com.ddmap.hadoop.db.util;import java.util.*;/** * Created by IntelliJ IDEA. * User: 杨果 * Date: 12-1-9 * Time: 上午10:50 * 该类是对Map的value进行排序的工具类 */public class SortMapByValue {    /***     *  升序     */    public static Map.Entry[] ascend(Map h) {        Set set = h.entrySet();        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set                .size()]);        Arrays.sort(entries, new Comparator() {            public int compare(Object arg0, Object arg1) {                Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());                Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());                return key1.compareTo(key2);            }        });        return entries;    }    public static void main(String[] args){         Map map=new HashMap();        map.put("a",1);        map.put("b",2);        map.put("c",-1);        map.put("d",9999);        Map.Entry[] entries= SortMapByValue.ascend(map);        for(int i=0;i<entries.length;i++){            Map.Entry entrie=entries[i];            System.out.println(entrie.getKey()+"="+entrie.getValue());        }    }}

?输出效果如下:

c=-1

a=1

b=2

d=9999

1 楼 wengzil 2012-01-09 1122[color=orange][/color][size=xx-small][/size] 2 楼 hubeen 2012-01-09 使用Treemap 3 楼 wengzil 2012-01-09 222222[quote1]11
[*]

[*]

[*]

[*]

[*]
[/color][color=white]

读书人网 >编程

热点推荐