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<Student> 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<Student>() {
@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<Map> studentList = new ArrayList();
Map map = new HashMap();map.put("姓名","张三");map.put("语文",60);map.put("数学",65);map.put("英语",70);
studentList.add(map);
map = new HashMap();map.put("姓名","李四");map.put("语文",80);map.put("数学",40);map.put("英语",50);
studentList.add(map);
map = new HashMap();map.put("姓名","王五");map.put("语文",70);map.put("数学",90);map.put("英语",30);
studentList.add(map);
System.out.println("排序前");
for (Map o : studentList) {
System.out.println(o.get("姓名")+" "+o.get("语文")+" "+o.get("数学")+" "+o.get("英语"));
}
Collections.sort(studentList, new Comparator<Map>() {
@Override
public int compare(Map o1, Map o2) {
//排序字段 正序 如果需要倒序则将两个值调换
return Integer.parseInt(o1.get("语文").toString())-Integer.parseInt(o2.get("语文").toString());
}
});
System.out.println("排序后");
for (Map o : studentList) {
System.out.println(o.get("姓名")+" "+o.get("语文")+" "+o.get("数学")+" "+o.get("英语"));
}
}
}
结果输出: