HashMap自定义排序

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-28 07:09   92   0
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

//排序
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);
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP