Silas Reinagel Silas Reinagel - 4 months ago 30
Java Question

Java List<Long> to LongStream

It seems like there should be a trivial way to do this, but I haven't been able to discover it.

How can you perform LongStream functions on a List of Long without using the mapToLong(...) function from the Stream library.

The reason I am wondering about this, is because mapping something to itself seems degenerate.

mapToLong(x -> x)


Is there a way to easily initialize a LongStream from a List?

This is my current working code:

public long getAverage(final List<Long> values)
{
return (long)values.stream().mapToLong(x -> x).average().getAsDouble();
}


Pseudocode sample for what I would like to do:

public long getAverage(final List<Long> values)
{
return (long)LongStream.fromList(values).average().getAsDouble();
}

Answer

How can you perform LongStream functions on a List of Long without using the mapToLong(...)?

You can't. A Stream<Long> is not a LongStream. Map to a LongStream like this:

values.stream().mapToLong(Long::longValue)....