【问题标题】:How to flatMapToLong a Stream<List<Long>>?如何 flatMapToLong 一个 Stream<List<Long>>?
【发布时间】:2015-01-14 05:52:13
【问题描述】:

我有这个方法:

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

toDigits 有这个签名:

List<Long> toDigits(long l)

在 flatMapToLong 线上它给出了这个错误

类型不匹配:无法从 Stream 转换为 LongStream

当我把它改成

flatMapToLong(x -> x)

我收到此错误

类型不匹配:无法从 List 转换为 LongStream

唯一有效的就是这个

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

【问题讨论】:

    标签: java collections lambda java-stream flatmap


    【解决方案1】:

    你传递给flatMapToLong的Function需要返回一个LongStream:

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

    如果您愿意,也可以拆分 flatMapToLong:

    return list
            .stream()
            .map(ClassOfToDigits::toDigits)
            .flatMap(List::stream)
            .mapToLong(Long::longValue)
            .sum();
    

    【讨论】:

      【解决方案2】:

      这似乎有效:

      public static long sumDigits(final List<Long> list) {
          return list.stream().mapToLong(l -> l).sum();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-14
        • 1970-01-01
        • 2020-09-04
        • 2018-04-07
        • 2019-06-26
        • 1970-01-01
        • 2014-07-26
        相关资源
        最近更新 更多