public class TreeMapTest1 {
public static void main(String[] args) {
Map<User,String> treeMap = new TreeMap();
User user = new User("zhangsan", 18, 1000);
User user2 = new User("lisi", 20, 1000);
User user3 = new User("wangwu", 30, 500);
treeMap.put(user, "张三");
treeMap.put(user2, "李四");
treeMap.put(user3, "王五");
Set<Map.Entry<User, String>> entries = treeMap.entrySet();
for (Map.Entry<User, String> entry : entries) {
System.out.println(entry.getKey() + "---------" + entry.getValue());
}
}
}
class User implements Comparable<User> {
String name;
int age;
double salary;
public User() {
}
public User(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(User o) {
if (this.salary > o.salary) { //递增模式反之递减
return 1;
} else if (this.salary < o.salary) {
return -1;
} else {
if (this.age > o.age) {
return 1;
} else if (this.age < o.age) {
return -1;
} else {
return 0;
}
}
}
@Override
public String toString() {
return this.name + "-" + this.age + "-" + this.salary;
}
}
网友评论