目录
jdk1.7List集合中按照对象中指定字段排序
jdk1.7List集合中按照map中指定字段排序
jdk1.7List集合中按照对象中指定字段排序
题目:现在有一个list集合、里面存放着多个Student对象,现要求按照Student的score进行排序
代码演示:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Student {
public Student(String name, int score) {
this.name = name;
this.score = score;
}
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public static void main(String[] args) {
Student student = new Student("张三",60);
Student student2 = new Student("李四",30);
Student student3 = new Student("王五",80);
Student student4 = new Student("赵六",90);
List studentList = new ArrayList<>();
studentList.add(student);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
System.out.println("排序前");
for (Student o : studentList) {
System.out.println(o.getName()+" "+o.getScore());
}
Collections.sort(studentList, new Comparator() {
@Override
public int compare(Student o1, Student o2) {
//排序字段 正序 如果需要倒序则将两个值调换
return o1.getScore()-o2.getScore();
}
});
System.out.println("排序后");
for (Student o : studentList) {
System.out.println(o.getName()+" "+o.getScore());
}
}
}
结果输出:
jdk1.7List集合中按照map中指定字段排序
题目:现在有一个list集合、里面存放着多个Map,Map中用于存储学生的姓名,语文成绩、数学成绩、英语成绩,现在需要按照语文成绩进行排序输出
代码演示:
import java.util.*;
public class Student {
public static void main(String[] args) {
List
结果输出:



