Map的遍历与排序
引言:集合是java比较重要的一个知识点,而集合的遍历尤为重要。
相对来说,Map又是集合中比较难懂的一部分,故今天来讲一下Map的
遍历与排序。
Map的遍历
较为简单的遍历方法可以通过
keySet()
方法获取Map中的所有的key
,
然后使用get(key)
获取key
对应的value
,代码如下:Map
map = new HashMap ();
map.put(“1”,”xinger”);
//······省略部分代码
for(String s : map.keySet()){
System.out.println(“key:”+s+”,”+”value:”+map.get(s));
}通过Map.entrySet()遍历map:Map.entrySet()方法返回该地图的集合视图(
Set(Map.Entry<K,V>)
)for(Map.Entry
entry : map.entrySet()){ //参数类型请灵活处理
System.out.println(“key:”+entry.getKey()+”,”+”value:”+entry.getValue());
}通过迭代器遍历Map:
Iterator(Map.Entry
) ite = map.entrySet().iterator();
while(ite.hasNext()){Map.Entry<String, String> entry = ite.next();
System.out.println("key:"+entry.getKey()+","+"value:"+entry.getValue());z
}
Map的排序
利用TreeMap类进行排序:
TreeMap
是默认按key
的升序排序,若要改变排序方式,需要使用比较器:Comparator
并使用构造器TreeMap(Comparator<? super K> comparator)
,注意到泛型? super K
,故本质还是进行按key
排序。Map
map = new TreeMap (new Comparator (){ @Override
public int compare(String o1, String o2) {
return o2.compareTo(p1);
});
Map按value排序:实现Comparator接口,并重写
compare(Object o1, Object o2)
方法List
> list = new ArrayList >(map.entrySet()); //排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){ //内部类
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
还没有评论,来说两句吧...