JAVA TreeMap之根据Values排序

Map<K,V>接口中主要包含两个实现类:

(1)HashMap<K,V>类, 它按照Hash映射存储的“键值"对存储对象。能够把它保存的记录根据键(key)排序,默认是按升序排序。

(2)TreeMap<K,V>类,它按照Hash映射存储的”键/值“对作为树节点存储对象。HashMap的值是没有顺序的,它是按照key的HashCode来实现的,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。


根据Values排序,此方法对HashMap<K,V>类,TreeMap<K,V>类适用

这里要说明的是并不是对TreeMap<K,V>本身进行排序,而是通过Map.Entry里的entrySet方法把所有的Key值和Values值取出来,放在了一个ArrayList集合里,再运用Collections类的方法进行排序。

import java.util.*;
import java.util.Map.Entry;

public class T_TreeMap {

	public static void main(String[] args) {
		HashMap<Integer,MyRectangle> hh = new HashMap<Integer,MyRectangle>();
		hh.put(2, new MyRectangle(3,6));
		hh.put(4, new MyRectangle(4,4));
		hh.put(1, new MyRectangle(3,7));
		hh.put(5, new MyRectangle(5,4));
		hh.put(3, new MyRectangle(6,2));
				
		List<Entry<Integer,MyRectangle>> list = new ArrayList<Entry<Integer,MyRectangle>>(hh.entrySet());	
		Collections.sort(list,new Comparator<Map.Entry<Integer,MyRectangle>>() {           			     
			public int compare(Entry<Integer,MyRectangle> o1, Entry<Integer,MyRectangle> o2) {             
				return o1.getValue().compareTo(o2.getValue());        
				}        
		});
		for (Entry<Integer,MyRectangle> e: list) {

			System.out.println(e.getKey()+":"+e.getValue().Getarea()+" "+e.getValue().Getzc());

		}
		Iterator<Entry<Integer, MyRectangle>> rr = hh.entrySet().iterator();
		while(rr.hasNext()) {
			MyRectangle r1 = rr.next().getValue();		
			System.out.println(" " +r1.Getarea());
		}
		
	}

}
public class MyRectangle implements Comparable<MyRectangle> {
int width;
int height;
public MyRectangle(int w, int h) {
	this.width = w;
	this.height = h;
}
public int Getarea() {
	return this.width*this.height;
}
public int Getzc() {
	return this.width+this.height;
}
	public int compareTo(MyRectangle m) {
		
		//return Integer.compare(m.Getarea(), this.Getarea());
		return Integer.compare(this.Getzc(), m.Getzc());
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值