package test2;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class treeMap {
public static void main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<>();
Student stu1 = new Student("张三",23);
Student stu2 = new Student("李四",26);
Student stu3 = new Student("王五",18);
tm.put(stu1,"香港");
tm.put(stu2,"台湾");
tm.put(stu3,"北京");
Set<Map.Entry<Student,String>> set = tm.entrySet();
for (Map.Entry<Student, String> studentStringEntry : set) {
Student key = studentStringEntry.getKey();
String value = studentStringEntry.getValue();
System.out.println(key+"-----"+value);
}
System.out.println("--------------------------------------------------");
tm.forEach(
(Student stu,String str)->{
System.out.println(stu+"-----"+str);
});
System.out.println("--------------------------------------------------");
Set<Student> keys = tm.keySet();
for (Student key : keys) {
String s = tm.get(key);
System.out.println(key+"-----"+s);
}
}
}
package test2;
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
int reasult = this.getAge() - o.getAge();
reasult = reasult == 0 ? this.getName().compareTo(o.getName()) : reasult;
return reasult;
}
}