我想使用 Java 流在 {1,...1000} 范围内找到一个整数 i,函数 sin(i/100) 是最小的。我尝试将 min 与比较器一起使用,如 this question :
Comparator<Integer> sineComparator = (i,j) ->
Double.compare(Math.sin(i/100.0), Math.sin(j/100.0));
IntStream.range(1,1000)
.min(sineComparator);
但它不起作用,因为 IntStream 没有接受比较器的 min 变体。我能做什么?
最佳答案
你必须使用 boxed()
转换 IntStream
至 Stream<Integer>
这将允许您使用 min
带有比较器:
IntStream.range(1, 1000)
.boxed()
.min(sineComparator)
或者,您可以避免装箱,但会降低清晰度:
IntStream.range(1,1000)
.reduce((i,j) -> sineComparator.compare(i, j) <= 0 ? i : j)
另外,您可以使用 Comparator.comparingDouble
创建比较器:
Comparator<Integer> sineComparator = Comparator.comparingDouble(i -> Math.sin(i/100.0));
关于concurrency - Arg-min 使用整数流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585709/