1、Collections.sort()
//升序排列 Collections.sort(list, new Comparator<Student>() { public int compare(Student s1, Student s2) { return s1.getAge().compareTo(s2.getAge()); } });
//降序排列 Collections.sort(list, new Comparator<Student>() { public int compare(Student s1, Student s2) { return s2.getAge().compareTo(s1.getAge()); } });
//多条件-先年龄升序、后分数升序 Collections.sort(list, new Comparator<Student>() { public int compare(Student s1, Student s2) { int i = s1.getAge().compareTo(s2.getAge()); if(i == 0) { i = s1.getScore().compareTo(s2.getScore()); } return i; } });
JDK1.8环境下可使用
2、list.sort()
//升序排列 list.sort((x,y)->Integer.compare(x.getAge(), y.getAge())); //降序排列 list.sort((x,y)->Integer.compare(y.getAge(), x.getAge()));
3、list.stream()
//升序排列 list = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList()); list = list.stream().sorted(Comparator.comparingInt(Student::getAge)).collect(Collectors.toList()); //使用lambda表达式 list = list.stream().sorted(Comparator.comparing(e -> e.getAge())).collect(Collectors.toList()); //降序排列 list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList()); 多条件-先年龄升序、后分数升序 list = list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Comparator.comparing(Student::getScore))).collect(Collectors.toList());