美文网首页
java面试常考题:HashMap根据key,value排序

java面试常考题:HashMap根据key,value排序

作者: 萤火之森ss | 来源:发表于2017-08-10 14:57 被阅读66次

Map<Integer,String> map = new HashMap<Integer,String>();

map.put(1,"一");

map.put(3,"三");

map.put(4,"四");

map.put(2,"二");

//要根据key,和value排序嘛,用到Collections.sort()的方法,

//首先将map转化为list

List<Map.Entry<Integer,String>> list = new LinkedList<Map.Entry<Integer,String>>(map.entrySet());

//entrySet() 方法/返回map中包含的映射关系的 Set 视图。

//Map.Entry表示映射关系,迭代后可以e.getKey(),e.getValue()取key和value

//哎。。。

Collections.sort(list,new Comparator<Map.Entry<Integer,String>>(){

                  @Overide

                  public int compare(Map.Entry<Integer,String> o1,Map.Entry<Integer,String> o2){

                  //根据key排序,根据value排序就getValue

                  returen 01.getKey() - 02.getKey();//正序,倒序 o2-o1

                  }

});

print 的list就是排好序的了,需要的话,在转化成map..

相关文章

网友评论

      本文标题:java面试常考题:HashMap根据key,value排序

      本文链接:https://www.haomeiwen.com/subject/loyhrxtx.html