是的,map集合中存的是键和值,键是一个set集合,可以对这个set集合进行指定顺序的排序。这有个示例:- package cn.itcast.day1;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeMap;
- class StuNameComparator implements Comparator<Student> {
- /* 按照姓名排序,如果姓名相同,那么按照年龄排序 */
- public int compare(Student o1, Student o2) {
- int num = o1.getName().compareTo(o2.getName());
- if (num == 0) {
- return o1.getAge() - o2.getAge();
- }
- return num;
- }
- }
- class Student /* implements Comparable<Student> */{// 十七具有比较性,防止排序的出现异常
- private String name;// 姓名
- private int age;// 年龄
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- /*
- // 重写hashCode()方法
- public int hashCode() {
- return this.name.hashCode() + this.age * 12;
- }
- //重写equals方法
- public boolean equals(Object ob) {
- if (!(ob instanceof Student))
- throw new ClassCastException("不是Student对象");
- Student stu = (Student) ob;
- return this.name.equals(stu.getName()) && this.age == stu.getAge();
- }
-
- // 覆写CompareTo方法 先比较年龄,然后比较姓名
-
- public int compareTo(Student stu) {
- int num = this.age - stu.age;
- if (num == 0) {
- return this.name.compareTo(stu.name);
- }
- return num;
- }
- */
- }
- public class TreeMapDemo {
- public static void main(String[] args) {
- /* 定义HashMap,里面存储的是Student和地址 */
- TreeMap<Student, String> map = new TreeMap<Student, String>(
- new StuNameComparator());
- map.put(new Student("java03", 23), "北京");
- map.put(new Student("net02", 21), "上海");
- map.put(new Student("net02", 26), "厦门");
- map.put(new Student("net03", 26), "广州");
- map.put(new Student("java01", 24), "南京");
- map.put(new Student("java01", 22), "天津");
- map.put(new Student("net03", 26), "广州");
- Set<Student> set = map.keySet();
- Iterator<Student> it = set.iterator();
- while (it.hasNext()) {
- Student stu = it.next();
- String name = stu.getName();
- int age = stu.getAge();
- String address = map.get(stu);
- System.out.println(name + ":" + age + ":" + address);
- }
- }
- }
复制代码 |