Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatMapToLong a Stream<List<Long>>?

I have this method:

public static long sumDigits(final List<Long> list) {
    return list
            .stream()
            .map(l -> toDigits(l))
            .flatMapToLong(x -> x.stream())
            .sum()
}

toDigits has this signature:

List<Long> toDigits(long l)

On the flatMapToLong line it gives this error

Type mismatch: cannot convert from Stream< Long > to LongStream

When I change it to

flatMapToLong(x -> x)

I get this error

Type mismatch: cannot convert from List< Long > to LongStream

The only thing that works is this

public static long sumDigits(final List<Long> list) {
    return list
            .stream()
            .map(l -> toDigits(l))
            .flatMap(x -> x.stream())
            .reduce(0L, (accumulator, add) -> Math.addExact(accumulator, add));
}
like image 917
mrt181 Avatar asked Jan 09 '23 10:01

mrt181


1 Answers

The Function you pass to flatMapToLong needs to return a LongStream :

return list
        .stream()
        .map(l -> toDigits(l))
        .flatMapToLong(x -> x.stream().mapToLong(l -> l))
        .sum();

You could also split up the flatMapToLong if you want:

return list
        .stream()
        .map(ClassOfToDigits::toDigits)
        .flatMap(List::stream)
        .mapToLong(Long::longValue)
        .sum();
like image 162
Alex - GlassEditor.com Avatar answered Jan 18 '23 09:01

Alex - GlassEditor.com