Java根据list中对象的某个属性降序排序
时间: 2023-09-27 16:05:47 浏览: 111
可以使用Comparator来实现:
1. 定义一个实现Comparator接口的类,实现compare方法,比较list中对象的某个属性,返回比较结果。
```java
public class MyComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o2.getProperty() - o1.getProperty(); //降序排列
}
}
```
2. 使用Collections.sort()方法进行排序,传入list和自定义的Comparator对象。
```java
List<MyObject> list = new ArrayList<>();
//添加元素
Collections.sort(list, new MyComparator());
```
完整示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortListByProperty {
public static void main(String[] args) {
List<MyObject> list = new ArrayList<>();
//添加元素
list.add(new MyObject("obj1", 5));
list.add(new MyObject("obj2", 3));
list.add(new MyObject("obj3", 7));
list.add(new MyObject("obj4", 2));
list.add(new MyObject("obj5", 9));
//使用自定义的Comparator进行降序排序
Collections.sort(list, new MyComparator());
//打印排序后的结果
for(MyObject obj : list) {
System.out.println(obj.getName() + " " + obj.getProperty());
}
}
//自定义对象
static class MyObject {
private String name;
private int property;
public MyObject(String name, int property) {
this.name = name;
this.property = property;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProperty() {
return property;
}
public void setProperty(int property) {
this.property = property;
}
}
//自定义Comparator
static class MyComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o2.getProperty() - o1.getProperty(); //降序排列
}
}
}
```
输出结果:
```
obj5 9
obj3 7
obj1 5
obj2 3
obj4 2
```
阅读全文