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