一个Java list 里面有多个数据对象,其中有一个字段是“grounding_state”,我仅需要从list里面取一条数据,根据“grounding_state”的值取数据的顺序为1>2>0>3>5,怎么实现
时间: 2024-03-12 15:47:23 浏览: 103
可以先定义一个根据“grounding_state”值排序的比较器类,然后使用Collections.sort()方法对list进行排序,最后取出第一个元素即可。
以下是示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<DataObject> list = new ArrayList<>();
list.add(new DataObject(2));
list.add(new DataObject(3));
list.add(new DataObject(1));
list.add(new DataObject(0));
list.add(new DataObject(5));
Collections.sort(list, new GroundingStateComparator());
DataObject result = list.get(0);
System.out.println(result.toString());
}
static class DataObject {
int groundingState;
public DataObject(int groundingState) {
this.groundingState = groundingState;
}
public int getGroundingState() {
return groundingState;
}
@Override
public String toString() {
return "DataObject{" +
"groundingState=" + groundingState +
'}';
}
}
static class GroundingStateComparator implements Comparator<DataObject> {
private final int[] order = {1, 2, 0, 3, 5};
@Override
public int compare(DataObject o1, DataObject o2) {
int index1 = getIndex(o1.getGroundingState());
int index2 = getIndex(o2.getGroundingState());
return Integer.compare(index1, index2);
}
private int getIndex(int groundingState) {
for (int i = 0; i < order.length; i++) {
if (groundingState == order[i]) {
return i;
}
}
return order.length;
}
}
}
```
输出结果为:
```
DataObject{groundingState=1}
```
阅读全文