应用场景:ArrayList里存储一坨对象,按照其中的某个属性,对整个ArrayList进行排序
class someDto{
private String id;
private double score;
someDto(String id, double score) {
this.id = id;
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
对包含一列someDto
的ArrayList
,进行排序:
- 按照
id
大小进行排序:
Comparator<someDto> cp = Comparator.comparing(someDto::getId);
dtos.sort(cp); // 顺序
dtos.sort(cp.reversed()); // 逆序
- 按照
score
大小进行排序:
(都能work,但最后一个似乎最好)
// Comparator<someDto> cp = (a, b) -> Double.compare(a.getScore(), b.getScore());
// Comparator<someDto> cp = Comparator.comparing(someDto::getScore);
Comparator<someDto> cp = Comparator.comparingDouble(someDto::getScore);
完整代码:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class someDto{
private String id;
private double score;
someDto(String id, double score) {
this.id = id;
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public class simpleCompare {
public static void main(String[] args) {
List<someDto> dtos = new ArrayList<>();
dtos.add(new someDto("a", 5));
dtos.add(new someDto("b", 3));
dtos.add(new someDto("c", 5));
dtos.add(new someDto("d", 8));
// Comparator<someDto> cp = (a, b) -> a.getScore() < b.getScore() ? -1 : 1;
// Comparator<someDto> cp = (a, b) -> Double.compare(a.getScore(), b.getScore());
// Comparator<someDto> cp = Comparator.comparing(someDto::getScore);
Comparator<someDto> cp = Comparator.comparingDouble(someDto::getScore);
// Comparator<someDto> cp = Comparator.comparing(someDto::getId);
dtos.sort(cp.reversed());
for(someDto dto : dtos) {
System.out.println("====");
System.out.println(dto.getId());
System.out.println(dto.getScore());
}
}
}