Map.Entry
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方法。
是在刷leedcode题学习用了下Map.Entry 223. Rectangle Area,我是用HashMap存入的输入信息的,下面就遇到了要对map的value排序的问题了
首先,如果要对map的key排序的话
如果是升序,那么TreeMap就可以解决了,因为TreeMap默认的就是升序,但是我们也可以使用Comparator来改变它的排序的方式。
package Map; import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) {
// TODO Auto-generated method stub Map<Integer,Integer> map=new TreeMap<Integer,Integer>(
new Comparator<Integer>(){
public int compare(Integer obj1,Integer obj2){
return obj1-obj2;//控制升序还是降序
//如果String则obj1.compareTo(obj2)
}
});
map.put(3, 1);
map.put(1, 1);
map.put(5, 1);
map.put(4, 1);
map.put(2, 1); Set<Integer> keySet=map.keySet();
Iterator<Integer> iter=keySet.iterator();
while(iter.hasNext()){
Integer key=iter.next();
System.out.println(key+":"+map.get(key));
}
}
}
然后,如果是对map的value排序的话
package Map; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; public class HashMapTest { public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(1, 3);
map.put(3, 5);
map.put(5, 1);
map.put(4, 2);
map.put(2, 4);
List<Map.Entry<Integer,Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){
public int compare(Entry<Integer,Integer>obj1,Entry<Integer,Integer>obj2){
return obj1.getValue()-obj2.getValue();
}
});
for (Map.Entry<Integer, Integer>mapp:list){
System.out.println(mapp.getKey()+":"+mapp.getValue()); }
}
}
其中 Lambda表达式之比较器参考了https://my.oschina.net/biezhi/blog/506433