Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct conversion from Collection<Long> 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.

like image 539
OllieStanley Avatar asked Mar 03 '23 12:03

OllieStanley


2 Answers

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() {}
} 
like image 108
Andrew Tobilko Avatar answered Mar 13 '23 07:03

Andrew Tobilko


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.

like image 26
bjmi Avatar answered Mar 13 '23 06:03

bjmi