gpt4 book ai didi

java - HashMap 的最大值打印为 NaN

转载 作者:行者123 更新时间:2023-11-30 06:52:05 28 4
gpt4 key购买 nike

我正在尝试打印 HashMap 的最大值。

它是一个静态变量,在Results.java中定义如下

public static HashMap<Double,Double> true_false=new LinkedHashMap<>();

我在另一个类中访问它,当我打印 HashMap 时它打印正常。

public double print_maxThreshold(){

double maxValueInMap = (Collections.max(Results.true_false.values()));

}

当 Results.true_false 打印结果如下。

{0.01=0.5714285714285714, 0.05=0.5714285714285714, 0.1=0.6190476190476191, 0.15000000000000002=0.5405405405405405, 0.2=0.5625, 0.25=0.5714285714285715, 0.3=0.34782608695652173, 0.35=0.3157894736842105, 0.39999999999999997=0.2222222222222222, 0.44999999999999996=0.11764705882352941, 0.49999999999999994=0.11764705882352941, 0.5499999999999999= Nan,0.6 = Nan,0.65 = Nan,0.70000000000001 = Nan,0.7500000000000001 = Nan,0.8000000000000002 = Nan,0.850000000000000002 = Nan,Nan,0.900000000002

但为什么最大值不打印为 0.6190476190476191

请好心人解释一下

最佳答案

Collections.max(Collection<? extends T> coll) 的 Javadoc说:

Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).

这意味着排序由 Double.compareTo(Double anotherDouble) 定义方法,它具有以下 javadoc 描述:

Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).

也就是说,如果有NaN集合中的值,max()将返回 NaN .


更新

排除NaN考虑使用 Java 8 流:

double maxValueInMap = Results.true_false
.values()
.stream()
.mapToDouble(Double::doubleValue)
.filter(d -> ! Double.isNaN(d))
.max()
.orElseThrow(NoSuchElementException::new);

这个比your self-answer的优势, 是它没有修改原来的 Map .

关于java - HashMap 的最大值打印为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553759/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com