- //treeMap,姓名小到大,年龄大到小
- package cn.itcast.practice;
- import java.util.Comparator;
- import java.util.Set;
- import java.util.TreeMap;
- public class TreeMapDemo {
- public static void main(String[] args) {
-
- Person p1=new Person("001",23);
- Person p2=new Person("001",24);
- Person p3=new Person("002",25);
- Person p4=new Person("003",26);
- Person p5=new Person("004",23);
- Person p6=new Person("005",25);
- TreeMap<Person,String> treeMap = new TreeMap<Person,String>(new Comparator<Person>(){
- @Override
- public int compare(Person p1, Person p2) {
- //姓名小到大,年龄大到小
- int num=p1.getName().compareTo(p1.getName());
- int num1=(num==0)? (p2.getAge()-p1.getAge()):num;
- return num1;
- }});
- treeMap.put(p1, "admin");
- treeMap.put(p2, "system");
- treeMap.put(p3, "scott");
- treeMap.put(p4, "scott");
- treeMap.put(p5, "scott");
- treeMap.put(p6, "system");
- System.out.println(treeMap.size());
- Set<Person> keys=treeMap.keySet();
- for (Person key : keys) {
- System.out.println(key.getName()+"---"+key.getAge()+"---"+treeMap.get(key));
- }
- }
- }
复制代码 |
|