Search code examples
javacollectionslambdajava-streamflatmap

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));
}

Solution

  • 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();