首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 企业软件 > 行业软件 >

关于地图的排序有关问题

2013-02-24 
关于map的排序问题MapString, Integer map new HashMapString, Integer()map.put(d, 2)map.put(

关于map的排序问题
Map<String, Integer> map = new HashMap<String, Integer>();map.put("d", 2);map.put("c", 1);map.put("b", 1);map.put("a", 3);List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());//排序前for (int i = 0; i < infoIds.size(); i++) { String id = infoIds.get(i).toString(); System.out.println(id);}//d 2//c 1//b 1//a 3//此处排序顺序不定,对于Map来说,并不是先进先出//排序Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { //return (o2.getValue() - o1.getValue()); return (o1.getKey()).toString().compareTo(o2.getKey()); }}); //排序后for (int i = 0; i < infoIds.size(); i++) { String id = infoIds.get(i).toString(); System.out.println(id);}//根据key排序//a 3//b 1//c 1//d 2//根据value排序//a 3//d 2//b 1//c 1

二、 关于 Map.entry

转自: http://hi.baidu.com/wh_fly/item/ec43afaf57c4a4dd5bf191b1

? Map是java中的接口,Map.Entry是Map的一个内部接口。

?????????Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。

?????????Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。

?????????

????????由以上可以得出,遍历Map的常用方法:

???????1.??Map?map?=?new?HashMap();

???????????Irerator?iterator?=?map.entrySet().iterator();

???????????while(iterator.hasNext())?{

???????????????????Map.Entry?entry?=?iterator.next();

???????????????????Object?key?=?entry.getKey();

???????????????????//

???????????}

???????2.Map?map?=?new?HashMap();?

???????????Set??keySet=?map.keySet();

???????????Irerator?iterator?=?keySet.iterator;

???????????while(iterator.hasNext())?{

???????????????????Object?key?=?iterator.next();

???????????????????Object?value?=?map.get(key);

???????????????????//

???????????}

?

???????另外,还有一种遍历方法是,单纯的遍历value值,Map有一个values方法,返回的是value的Collection集合。通过遍历collection也可以遍历value,如

??????Map?map?=?new?HashMap();

??????Collection?c?=?map.values();

??????Iterator?iterator?=?c.iterator();

??????while(iterator.hasNext())?{

?????????????Object?value?=?iterator.next();?

?????}

热点排行
Bad Request.