实现
student类实现 Comparable接口 并且重写compareTo(Student1 o)方法
调用sort(List list, Comparator super T> c),重写匿名类的 compare(T o1,T o2 ) 方法即可
转成stream,再调用sorted,同2匿名内部类重写方法,list.stream().sorted(Comparator super T> comparator)
lambda方法,看起来最简洁清爽,引用对象的方法 类::实例方法
list2.stream().sorted(Comparator.comparing(Student2::getScore).thenComparing(Student2::isGreat));
代码总结
package com.mycollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MySort {
/**
* 排序
* 1、实现Comparetor接口 重写Compare方法
* 2、使用Collections.xx方法
* 3、使用lamdba表达式
*/
static class Student1 implements Comparable{
private int score;
private boolean great;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean isGreat() {
return great;
}
public void setGreat(boolean great) {
this.great = great;
}
public Student1(int score, boolean great) {
this.score = score;
this.great = great;
}
@Override
public int compareTo(Student1 o) {
if(this.score>o.score){
return -1;
}else if(this.score == o.score&&this.great){
return -1;
}else{
return 1;
}
}
@Override
public String toString() {
return "Student1{" +
"score=" + score +
", great=" + great +
"}";
}
}
static class Student2{
private int score;
private boolean great;
public int getScore() {
return score;
}
public Student2(int score, boolean great) {
this.score = score;
this.great = great;
}
public void setScore(int score) {
this.score = score;
}
public boolean isGreat() {
return great;
}
public void setGreat(boolean great) {
this.great = great;
}
@Override
public String toString() {
return "Student2{" +
"score=" + score +
", great=" + great +
"}";
}
}
public static void main(String[] args) {
// 需要成绩好的,优等生排前面
// 第一种,就是实现接口 List list1 = new ArrayList();
list1.add(new Student1(50,true));
list1.add(new Student1(50,false));
list1.add(new Student1(30,true));
list1.add(new Student1(60,true));
Collections.sort(list1);
list1.stream().forEach(student1-> System.out.println(student1));
// 第二种,实体类不需要
List list2 = new ArrayList();
list2.add(new Student2(50,true));
list2.add(new Student2(50,false));
list2.add(new Student2(30,true));
list2.add(new Student2(60,true));
Collections.sort(list2,(o1,o2)->{
if(o1.score
return 1;
}else if(o1.score == o2.score&&o2.great){
return 1;
}else{
return -1;
}
});
list2.stream().forEach(student-> System.out.println(student));
//3、 sorted 把匿名内部类丢进去,和第二种差不多
list2.stream().sorted((o1,o2)->{
if(o1.score>o2.score){
return 1;
}else if(o1.score == o2.score&&o1.great){
return 1;
}else{
return -1;
}
});
// 4、 lamdba 类::方法 comparing方法、 thenComparing
list2.stream().sorted(Comparator.comparing(Student2::getScore).thenComparing(Student2::isGreat));
System.out.println(Arrays.toString(list2.toArray()));
}
}