0
点赞
收藏
分享

微信扫一扫

HashMap的倒序排序

千妈小语 2022-02-17 阅读 117
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());
	}
 
}

 文章转载:

HashMap的倒序排序

举报

相关推荐

0 条评论