大家好,今天给大家带来的是Java中集合排序的小练习:
自定义类有三个属性:
姓名、年龄、分数。
使用Map集合对自定义类的对象进行排序,规则如下:
规则一:先按照年龄从大到小排序
规则二:如果年龄相同则按照分数从小到大排序
本题核心在于实现Comparable接口 ,根据需求重写compareTo方法;
下面上代码~
package com.test.work03;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Test04 {
public static void main(String[] args) {
Map<Student, Integer> map = new TreeMap<Student, Integer>();
Student s1 = new Student("王1", 18, 99);
Student s2 = new Student("王2", 17, 94);
Student s3 = new Student("王3", 19, 96);
Student s4 = new Student("王4", 18, 100);
map.put(s1, 1);
map.put(s2, 2);
map.put(s3, 3);
map.put(s4, 4);
Set<Student> keySet = map.keySet();
for (Student s : keySet) {
System.out.println(s);
}
}
}
class Student implements Comparable<Student>{
private String name;
private Integer age;
private Integer score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public Student(String name, Integer age, Integer score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
public Student() {
// TODO Auto-generated constructor stub
}
@Override
public int compareTo(Student o) {
if(this.age!=o.age) {
int n = o.getAge()-this.age;
return n;
}else {
int n2 = this.score - o.getScore();
return n2;
}
}
}
下面是效果图:先按年龄从大到小,如果年龄相同,按成绩从小到大
今天的分享结束啦,希望对大家有帮助哦~~