HashMap的倒序排序

public class TestShort {

	public static void main(String[] args) {
		
		
	//  需求:对hashmap的value的值的大小进行逆序排序
		

		// 创建一个HashMap 然后填充数据
		HashMap<String, Integer> oldhMap = new HashMap<>();
		oldhMap.put("a", 12);
		oldhMap.put("b", 53);
		oldhMap.put("c", 41);
		oldhMap.put("d", 24);

		HashMap<String, Integer> newMap = sortMap(oldhMap);

		printMap(oldhMap, newMap);

	}

	
	/**
	 * 对map集合进行逆序排序
	 * @param oldhMap
	 * @return
	 */
	private static HashMap<String, Integer> sortMap(HashMap<String, Integer> oldhMap) {
		
		/*
		 *   在 Collections 有个排序的方法  sort(List<T> list, Comparator<? super T> comparator)
		 *   第一个参数为List map无法使用 所以要想办法把map转化为List
		 */
		
		//把map转成Set集合
		Set<Entry<String, Integer>> set = oldhMap.entrySet();
		
		//通过set 创建一个 ArrayList 集合
		ArrayList<Entry<String, Integer>> arrayList = new ArrayList<>(set);

		//对arraylist进行倒序排序
		Collections.sort(arrayList, new Comparator<Entry<String, Integer>>() {

			@Override
			public int compare(Entry<String, Integer> arg0,
					Entry<String, Integer> arg1) {
				//逆序 就用后面的参数 - 前面的参数
				return arg1.getValue() - arg0.getValue();
			}
		});
		
		
		//创建一个map
		LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

		for (int i = 0; i < arrayList.size(); i++) {
			Entry<String, Integer> entry = arrayList.get(i);
			map.put(entry.getKey(), entry.getValue());
		}

		return map;
	}

	
	/**
	 * 打印map集合
	 * @param oldhMap 老集合
	 * @param newMap   排序后的新集合
	 */
	private static void printMap(HashMap<String, Integer> oldhMap,
			HashMap<String, Integer> newMap) {
		
		System.out.println(oldhMap.toString());
		System.out.println(oldhMap.toString());
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值