首页 技术 正文
技术 2022年11月13日
0 收藏 997 点赞 3,600 浏览 1892 个字

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905