实现结果:
TreeMapTest实现排序:
package com.xm.hashmap; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { System.out.println("--------begin------"); Person p1=new Person("马先生","1000"); Person p2=new Person("李先生","2000"); Person p3=new Person("王先生","3000"); Map<Number, Person> map=new HashMap<Number,Person>(); map.put(Integer.parseInt(p1.getAge()), p1); map.put(Integer.parseInt(p2.getAge()), p2); map.put(Integer.parseInt(p3.getAge()), p3); System.out.println("HashMap实现的map集合,无顺序"); for(Iterator<Number> it=map.keySet().iterator();it.hasNext();){ Person person =map.get(it.next()); System.out.println(person.getName()+" "+person.getAge()); } System.out.println("TreeMap实现的map集合,升序"); Map<Number, Person> treeMap=new TreeMap<Number ,Person>(); treeMap.putAll(map); for(Iterator it =treeMap.keySet().iterator();it.hasNext();){ Person person=treeMap.get(it.next()); System.out.println(person.getName()+" "+person.getAge()); } System.out.println("TreeMap实现的map集合,降序"); Map<Number, Person> treeMap2=new TreeMap<Number ,Person>(Collections.reverseOrder());//初始化为反转排序 treeMap2.putAll(map); for(Iterator it =treeMap2.keySet().iterator();it.hasNext();){//遍历集合 Person person=treeMap2.get(it.next()); System.out.println(person.getName()+" "+person.getAge()); } System.out.println("--------end------"); } }
Person实体:
package com.xm.hashmap; public class Person { String name; String age; public Person(String name,String age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }