3

I would like to find, using Java streams, an integer i, in the range {1,...1000}, for which the function sin(i/100) is smallest. I tried to use min with comparator, as in 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);

but it did not work since an IntStream does not have a variant of min that accepts a comparator. What can I do?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183

1 Answers1

5

You have to use boxed() to convert IntStream to Stream<Integer> which will allow you to use min with a comparator:

IntStream.range(1, 1000)
            .boxed()
            .min(sineComparator)

Alternatively, you can avoid boxing but at the cost of reduced clarity:

IntStream.range(1,1000)
            .reduce((i,j) -> sineComparator.compare(i, j) <= 0 ? i : j)

On a separate note, you can create your comparator using Comparator.comparingDouble:

Comparator<Integer> sineComparator = Comparator.comparingDouble(i -> Math.sin(i/100.0));
Misha
  • 27,433
  • 6
  • 62
  • 78