import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; //comparator、comparable的用法(按照要求将map集合的键值对进行顺序输出) import java.util.List; public class Test { public static <T> void sop(T t) { System.out.println(t); } public static void main(String args[]) throws Exception { // 创建一个map集合,用来存储数据 <>表示接收的是泛型,即指定的类型 List<Person> list = new ArrayList<Person>(); // 往集合添加数据 list.add(new Person("czhangsan1", "11", "beijing")); list.add(new Person("zhangsan5", "15", "nanjing")); list.add(new Person("azhangsan5", "10", "shanghai")); list.add(new Person("zhangsan2", "20", "haierbing")); list.add(new Person("bzhangsan2", "20", "beijing")); list.add(new Person("zhangsan3", "12", "shanghai")); list.add(new Person("zhangsan4", "19", "changchun")); list.add(new Person("zhangsan4", "10", "changchun")); list.add(new Person("zhangsan4", "10", "zhengzhou")); // 将map集合转换为set集合,因为map集合没有迭代器 ,而set集合有 Collections.sort(list); System.out.println("按年龄排序:"); for (Person person : list) { System.out.println(person.toString()); } Collections.sort(list, new MyCompare()); System.out.println("按姓名排序:"); for (Person person : list) { System.out.println(person.toString()); } } } class Person implements Comparable<Person>// 使Person的属性具有比较性 { private String name; private String age; private String address; public Person(String name, String age, String address)// 初始化 { this.name = name; this.age = age; this.address = address; } 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "姓名:" + name + ", 年龄:" + age + ", 地址:" + address; } // 按年龄大小排序规则 @Override public int compareTo(Person o) { return this.age.compareTo(o.getAge()); } } // 按姓名字典顺序排序 class MyCompare implements Comparator<Person>// 自定义一个比较器 { @Override public int compare(Person o1, Person o2) { return o1.getName().compareTo(o2.getName()); } } // 注意:上面的两种形式都实现了比较,任选其中一种就可以。要么实现comparable接口;要么在集合中传入自定义的比较器。