【问题标题】:Cannot save result to List<Long> after manipulating two streams操作两个流后无法将结果保存到 List<Long>
【发布时间】:2017-10-10 17:54:44
【问题描述】:

我正在过滤两个流并在中间进行除法,但最后我无法将结果收集到列表中。你能告诉我我做错了什么吗?

这是我的代码

List<Long> average_population = total_population.stream() 
    .flatMapToLong( a-> number_of_cities.stream().mapToLong( b-> b/a ))
    .collect(null, Collectors.toList() );   <- error

这是我在最后一行遇到的错误。

LongStream 类型中的方法 collect(Supplier, ObjLongConsumer, BiConsumer) 不适用于参数 (null, Collector>) 类型不匹配:无法从 Collector> 转换为 ObjLongConsumer

【问题讨论】:

    标签: java lambda collections


    【解决方案1】:

    LongStream.collect 需要 3 个参数。 您可能正在寻找这个:

    List<Long> average_population =
      total_population.stream()
        .flatMapToLong(a -> number_of_cities.stream().mapToLong(b -> b / a))
        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    

    但实际上,坚持Long并没有给你带来太多好处, 使用flatMap 编写会更简单, 这将使您也可以使用更简单的collect

    List<Long> average_population =
      total_population.stream()
        .flatMap(a -> number_of_cities.stream().map(b -> b / a))
        .collect(Collectors.toList());
    

    【讨论】:

      【解决方案2】:

      如果您想在List&lt;Long&gt; 中收集结果,您需要将这些值装箱。 flatMapToLong 给出了一个LongStream,它给出了原始的long,而不是装箱的Long。您可以使用 .boxed() 运算符从长流中制作装箱对象。

      LongStream.of(1l, 2l, 3l).boxed().collect(Collectors.toList());
      

      所以我猜它会变成:

      List<Long> average_population = total_population.stream()
            .flatMapToLong(a -> number_of_cities.stream().mapToLong(b -> b / a))
            .boxed()
            .collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        相关资源
        最近更新 更多