我试图在我的查询结果中获取具有最小距离、最小速度和最大速度
的记录。目前我正在获得最短距离,但我在获得最小和最大速度方面遇到了问题,我问自己是否可以在 中添加另一个
类来实现它,但我收到错误 public int compareTo(BehaviourItem otherItem)
方法>BehaviourItemDuplicate method compareTo(BehaviourItem) in type BehaviourItem
。
如何从 BehaviourItem
类中获取最小和最大速度?
代码:
PreparedStatement prepared = con
.prepareStatement("SELECT speed, stop_distance from behaviour where mac = ? and stop_name = ?");
prepared.setString(1, macD);
prepared.setString(1, sto_nam);
ResultSet rsBehav = prepared.executeQuery();
List<BehaviourItem> behavList = new ArrayList<BehaviourItem>();
while (rsBehav.next()) {
int distance = rsBehav.getInt("stop_distance");
int speed = rsBehav.getInt("speed");
BehaviourItem behItem = new BehaviourItem(distance, speed);
behavList.add(behItem);
}
Collections.sort(behavList);
int minDistance = behavList.get(0).getDistance();
BehaviourItem 类:
public class BehaviourItem implements Comparable<BehaviourItem>{
int speed;
int distance;
public BehaviourItem(int speed, int distance) {
super();
this.speed = speed;
this.distance = distance;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
@Override
public int compareTo(BehaviourItem otherItem) {
// TODO Auto-generated method stub
return Integer.compare(this.distance, otherItem.distance);
}
}
最佳答案
您不应该让 BehaviourItem
实现 Comparable
,因为它没有自然顺序。相反,实现不同的 Comparator
s对于不同的属性。
请注意,在 Java 8 中,您可以简单地实现这样一个Comparator
Comparator<BehaviourItem> orderBySpeed=Comparator.comparingInt(BehaviourItem::getSpeed);
相当于
Comparator<BehaviourItem> orderBySpeed=new Comparator<BehaviourItem>() {
public int compare(BehaviourItem a, BehaviourItem b) {
return Integer.compare(a.getSpeed(), b.getSpeed());
}
};
或
Comparator<BehaviourItem> orderByDistance
=Comparator.comparingInt(BehaviourItem::getDistance);
对于其他属性。
几乎每个使用顺序的集合方法都有一个重载支持传递一个 Comparator
来定义顺序而不是使用自然顺序:
Collections.sort(behavList, orderBySpeed);
回复
Collections.sort(behavList, orderByDistance);
您甚至可以临时创建比较器:
Collections.sort(behavList, Comparator.comparingInt(BehaviourItem::getDistance));
和
Collections.sort(behavList, Comparator.comparingInt(BehaviourItem::getSpeed));
但是流 API 允许您在不排序的情况下查找最小值或最大值:
Optional<BehaviourItem> minBySpeed=behavList.stream()
.max(Comparator.comparingInt(BehaviourItem::getSpeed));
关于java - 使用 Comparable 获取多个项目的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979277/