map集合的排序

1、map集合的排序

package com.jlwang.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TestMapSort 
{
	
	private Map<String, Integer> map_datas = new HashMap<String, Integer>();


	public static void main(String[] args) 
	{
		TestMapSort instance = new TestMapSort();
		
		instance.initMap();
		
		//排序前
//		instance.printMap();
		
		instance.printMapSortAfter();
	}
	
	public void initMap()
	{
		map_datas.put("A", 90);
		map_datas.put("B", 50);
		map_datas.put("C", 70);
		map_datas.put("D", 60);
		map_datas.put("F", 30);
	}
	
	public  void printMapSortBefore()
	{
		Iterator<String> it = map_datas.keySet().iterator();
		
		while(it.hasNext())
		{
			String key = it.next();
			System.out.println(key+" : "+map_datas.get(key));
		}
		
	}
	
	public void printMapSortAfter()
	{
		List<Map.Entry<String, Integer>> list_datasList = new ArrayList<Map.Entry<String, Integer>>(map_datas.entrySet());
		
		Collections.sort(list_datasList,new Comparator<Map.Entry<String, Integer>>(){

			@Override
			public int compare(Entry<String, Integer> o1,
					Entry<String, Integer> o2) 
			{
				// TODO Auto-generated method stub
				return o2.getValue() - o1.getValue();
			}
			
		});
		
		
		//输出排序后结果
//		this.printMapSortBefore();
		
		for (int i = 0; i < list_datasList.size(); i++) 
		{
			String key = list_datasList.get(i).getKey();
			int value = list_datasList.get(i).getValue();
			
			System.out.println(key + " : "+value);
		}
	}
	
	
	public Map<String, Integer> getMap_datas() {
		return map_datas;
	}

	public void setMap_datas(Map<String, Integer> map_datas) {
		this.map_datas = map_datas;
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值