Skip to content
Advertisement

Direct conversion from Collection to LongStream

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.

Advertisement

Answer

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() {}
} 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement