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());
}
}