我必须对名称和年龄的基础知识进行排序。数据
,输出必须是
Arun 25 阿伦20 Bucky 22
这里是编码
import java.util.Comparator;
public class Student implements Comparable<Student> {
int id;
String name;
int age;
public int compareTo(Student s1) {
return this.age-s1.age;
}
//Constructor
public Student(String name,int id,int age) {
// TODO Auto-generated constructor stub
this.name="";
this.id=0;
this.age=0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
这里是主要的课程
import java.util.ArrayList;
import java.util.Collections;
public class StudentList {
public static void main(String args[]){
ArrayList<Student> list=new ArrayList<Student>();
Student s1= new Student(null, 0, 0);
s1.setName("Andy");
s1.setAge(25);
s1.setId(1);
Student s2=new Student(null, 0, 0);
s2.setName("Brad");
s2.setAge(22);
s2.setId(2);
Student s3=new Student(null, 0, 0);
s3.setName("Andy");
s3.setAge(30);
s3.setId(3);
list.add(s1);
list.add(s2);
list.add(s3);
Collections.sort(list);
for(Student a:list){
System.out.println(a.getName()+""+a.getAge());
}
}
}
答案 0 :(得分:3)
您应该更改compareTo()
方法:
public int compareTo(Student s1) {
int nameCompare = this.name.compareTo(s1.name == null ? "" : s1.name);
if(nameCompare == 0) return Integer.compare(this.age, s1.age);
return nameCompare;
}
答案 1 :(得分:0)
使用java8的流功能定义2个比较器(一个按名称,一个按年龄)
List<Student> list = new ArrayList<>();
Comparator<Student> byName = (x, y) -> x.name.compareTo(y.name);
Comparator<Student> byAge = (l, r) -> Integer.compare(r.age, l.age);
list.add(new Student("Andy", 25, 1));
list.add(new Student("Brad", 22, 2));
list.add(new Student("Andy", 30, 3));
list.stream().sorted(byName.thenComparing(byAge)).forEach(System.out::println);
然后流 - &gt;已排序 - &gt;然后比较(这是诀窍是第一个标准返回它们是相同的:))
答案 2 :(得分:0)
您是否可以使用Java-8
?您可以使用Comparator.comparing
方法。例如:
list.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getName));
它将根据年龄对学生列表进行排序,然后根据姓名;或者,如果您不想更改原始列表中元素的顺序,则可以使用Stream#sorted
:
List<Student> sorted = list.stream().
sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getName).
collect(Collectors.toList());
我希望这会有所帮助。
答案 3 :(得分:0)
Arun 20 Bucky 22 Arun 25
,输出必须是
Arun 25 Arun 20 Bucky 22
您希望按名称ASC排序,然后按年龄DESC
排序以这种方式实施Comparable:
public int compareTo(Student other) {
int nameComparison = String.compare(this.name, other.name)
if (nameComparison != 0){
return nameComparison;
}
// DESC order
return -Integer.compare(age, other.age);
}