- 实体实现 Comparable 接口
@Data
public class Example implements Comparable <Example> {
private String name;
private Integer age;
public Example(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Example example = (Example) o;
return Objects.equals(name, example.name) &&
Objects.equals(age, example.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public int compareTo(Example o) {
if (o.age.equals(this.age)) {
return this.name.compareTo(o.name);
}else {
return o.age-this.age;
}
}
public static void main(String[] args) {
Example example0 = new Example("张三", 9);
Example example1 = new Example("张三", 4);
Example example2 = new Example("离三", 6);
List<Example> demo = new ArrayList<>();
demo.add(example0);
demo.add(example1);
demo.add(example2);
Collections.sort(demo);
System.out.println(demo);
}
}
[
Example(name=张三, age=9),
Example(name=离三, age=6),
Example(name=张三, age=4)
]
- 使用匿名内部类进行排序
public static void main(String[] args) {
Example example0 = new Example("张三", 9);
Example example1 = new Example("张三", 4);
Example example2 = new Example("离三", 6);
List<Example> demo = new ArrayList<>();
demo.add(example0);
demo.add(example1);
demo.add(example2);
Collections.sort(demo,new Comparator<Example> (){
@Override
public int compare(Example o1, Example o2) {
return o2.age-o1.age;
}
});
System.out.println(demo);
}
[
Example(name=张三, age=9),
Example(name=离三, age=6),
Example(name=张三, age=4)
]
- stream 排序
public static void main(String[] args) {
Example example0 = new Example("张三", 9);
Example example1 = new Example("张三", 4);
Example example2 = new Example("离三", 6);
List<Example> demo = new ArrayList<>();
demo.add(example0);
demo.add(example1);
demo.add(example2);
demo = demo.stream().sorted(
Comparator.comparing(Example::getAge)
.reversed())
.collect(Collectors.toList());
System.out.println(demo);
}
[
Example(name=张三, age=9),
Example(name=离三, age=6),
Example(name=张三, age=4)
]