Search code examples
javalambdajava-streamjava-12

Avoiding unnamed lambda parameter


I have an application that needs to manage a priority queue of some items, where the priorities themselves can actually be fractional quantities (like 2.4 or 0.3). Smaller is better, as with usual integer priorities. The following one-liner generates a DoubleStream with DEFAULT_CAPACITY - many doubles pseudo-uniformly distributed between 0 and SCALE:

DoubleStream priorities = IntStream.range(0, DEFAULT_CAPACITY).map(_ -> r.nextDouble() * SCALE);

My question is: how can I avoid the unnamed parameter _ in the lambda that is given as an argument to map? Unfortunately, Random::nextDouble() is not static, so a method reference is not possible.

This question generalizes, of course: lacking a static method and given a known number of iterations, how can we avoid an unnecessary unnamed lambda parameter? Effectively, the generation of an intermediate Stream (the result of calling IntStream::range()), should really not be necessary.

// Edit: After looking at my IDE a bit closer, I am noting that the syntax above is actually NOT compilable since Java 9! The compiler says: As of Java 9, '_' is a keyword, and may not be used as an identifier. So this question is even more important to me now :)


Solution

  • Assuming you have a Random r object already:

    DoubleStream priorities = r.doubles(DEFAULT_CAPACITY, 0.0, SCALE);
    

    or

    DoubleStream priorities = DoubleStream
        .generate(() -> r.nextDouble() * SCALE)
        .limit(DEFAULT_CAPACITY);