I have a Collection<Long>
(obtained from a Map<UUID, Long>
's values()
method) and I would like to convert it into a LongStream
.
The simplest way I can think of is:
LongStream stream = map.values().stream().mapToLong(Long::longValue);
However it strikes me that there should be a simpler way to obtain primitive streams from Collections of boxed equivalents.
I checked StreamSupport
and could only find StreamSupport.longStream(Spliterator.OfLong spliterator, boolean parallel)
, but there doesn't appear to be a simple way to obtain an OfLong
spliterator instance from a Collection<Long>
either.
I could of course create my own utility function which performs the above mapToLong
functionality but if there's something built-in I'd rather use that. Apologies also if this has already been asked - I had a search but could find nothing.
LongStream stream = map.values().stream().mapToLong(Long::longValue);
There are no shortcuts (or handy transition methods) in the standard library. I don't see anything wrong or verbose with the approach you mentioned. It's simple and straightforward, why would you need to look for something else?
You could create your own utility class to support it, though I don't think it would be extremely helpful.
public final class Streams {
public static LongStream toLongStream(Stream<Long> stream) {
return stream.mapToLong(Long::longValue);
}
public static Stream<Long> toStreamLong(LongStream stream) {
return stream.boxed();
}
private Streams() {}
}
Just let the compiler decide how to unbox Long
instead of dictating him to call Long.longValue()
.
Straightforward:
Map<UUID, Long> map ...
LongStream stream = map.values().stream().mapToLong(l -> l);
or give this lambda a name and get a more readable version:
LongStream stream = map.values().stream().mapToLong(unbox())
ToLongFunction<Long> unbox() {
return l -> l;
}
Maybe there is a unboxed()
method as a counterpart to boxed()
someday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With