我有List
的{{1}}:
Doubles
我需要从该列表中找到给定值的最接近值。我在下面的解决方案中尝试了SO的另一个答案,但是到目前为止,这仍然行不通,List<Double> aList = Arrays.asList(100.33,300.99,600.0,900.44,1200.88,1500.15);
始终为0。
下面是我正在检查的解决方案:
idx
答案 0 :(得分:3)
您应该使用差的绝对值,并且它可能大于或小于0
尝试
private Double chekcer() {
int myNumber = 900;
double distance = Math.abs(aList.get(0)- myNumber);
int idx = 0;
for (int c = 1; c < aList.size(); c++) {
double cdistance = Math.abs(aList.get(c) - myNumber);
if (cdistance < distance) {
idx = c;
distance = cdistance;
}
}
Log("",...);
return aList.get(idx);
}
修改
这是我的全部代码,
public static void main(String[] args) {
System.out.println(chekcer());
}
private static Double chekcer() {
List<Double> aList = Arrays.asList(100.33,300.99,600.0,900.44,1200.88,1500.15);
int myNumber = 900;
double distance = Math.abs(aList.get(0)- myNumber);
int idx = 0;
for (int c = 1; c < aList.size(); c++) {
double cdistance = Math.abs(aList.get(c) - myNumber);
if (cdistance < distance) {
idx = c;
distance = cdistance;
}
}
return aList.get(idx);
}
输出
900.44
答案 1 :(得分:1)
在Java 8中: 您可能会发现该代码很有用
private static Double chekcer() {
List<Double> aList = Arrays.asList(100.33,300.99,600.0,900.44,1200.88,1500.15);
int myNumber = 900;
return aList.stream().min(Comparator.comparingDouble(i -> Math.abs(i - myNumber))).orElse(null);
}