Map<k,v>按value值降序排序

1.value值为基本类型:

public static Map<String, Long> sortByValue(Map<String, Long> map) {
		List<Map.Entry<String, Long>> list = new LinkedList<>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {

			public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
				Long result = o2.getValue() - o1.getValue();
				if (result > 0)
					return 1;
				else if (result == 0)
					return 0;
				else
					return -1;
			}
		});

		Map<String, Long> result = new LinkedHashMap<>();
		int i = 1;
		for (Map.Entry<String, Long> entry : list) {
			result.put(entry.getKey(), entry.getValue());
			System.err.println("第" + i + "名对应的groupId为" + entry.getKey() + ",对应的值为" + entry.getValue());
			i++;
		}
		return result;
	}

2.value值为数组类型(依次排序数组对应的元素);

public static Map<String, Long> sortByArrayValue(Map<String, long[]> map) {
		Map<String, Long> map2 = new HashMap<String, Long>();
		Map<String, Long> result = new LinkedHashMap<>();
		// 将i时刻的值存入新的map2,并排序输出到一个数组中
		for (int i = 0; i < 24; i++) {
			for (String key : map.keySet()) // 循环便利map
			{
				map2.put(key, map.get(key)[i]);
			}
			List<Map.Entry<String, Long>> list = new LinkedList<>(map2.entrySet());
			Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {

				public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
					Long result = o2.getValue() - o1.getValue();
					if (result > 0)
						return 1;
					else if (result == 0)
						return 0;
					else
						return -1;
				}
			});
			int j = 1;
			for (Map.Entry<String, Long> entry : list) {
				result.put(entry.getKey(), entry.getValue());
				System.err
						.println("第" + i + "时刻,第" + j + "名对应的groupId为" + entry.getKey() + ",对应的值为" + entry.getValue());
				j++;
			}
			System.out.println();
		}
		return result;
	}

参照:

 1.http://blog.sina.com.cn/s/blog_8e6f1b330101h7fa.html 

 2.http://www.cnblogs.com/liu-qing/p/3983496.html   通用升序

 3.http://blog.csdn.net/tsingheng/article/details/7909861  实例升序

 4.http://www.linuxidc.com/Linux/2013-11/92867.htm       降序




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值