代码之家  ›  专栏  ›  技术社区  ›  XtremeBaumer

如何连接两个intstreams?

  •  7
  • XtremeBaumer  · 技术社区  · 6 年前

    我想创建一个 List<String> 数值范围为72-129和132-200。我想用一个 IntStream 将值映射到字符串并收集到列表中。我用了这个代码:

    List<String> strings72to200 = Stream
            .concat(Stream.of(IntStream.range(72, 129)), Stream.of(IntStream.range(132, 200)))
            .map(e -> String.valueOf(e)).collect(Collectors.toList());
    

    但是,如果我调试 strings72to200 我得到这个:

    [java.util.stream.IntPipeline$Head@56d13c31, java.util.stream.IntPipeline$Head@5f9127c5]
    

    我相信 Stream.concat() 以及 .map() 导致了这一点,因为我有一段这样的代码:

    List<String> strings50to59 = IntStream.range(50, 60).mapToObj(e -> String.valueOf(e))
            .collect(Collectors.toList());
    

    注意这件作品使用 .mapToObj() 而不是 图() .

    因此,问题是,如何通过流(因为这看起来比循环更平滑)创建具有这些值(注意初始拆分)的列表?我是否应该创建完整的列表,然后删除不需要的项目(在较大的差距上不可行)?

    2 回复  |  直到 6 年前
        1
  •  6
  •   ernest_k Petronella    6 年前

    你要传球给 concat Stream<IntStream> ,不起作用(您需要整数流)。你得给它两个 Stream<Integer> :

    List<String> strings72to200 = Stream
            .concat(IntStream.range(72, 129).boxed(), 
                    IntStream.range(132, 200).boxed())
            .map(String::valueOf)
            .collect(Collectors.toList());
    

    如果你想包括 129 200 在溪流中,你应该使用 IntStream.rangeClosed (结束是独占的)

        2
  •  4
  •   Naman    6 年前

    你可能只是在找 boxed 在那里得到一个 Stream<Integer> 然后连接:

    List<String> strings72to200 = Stream.concat(
                IntStream.range(72, 129).boxed(), // to convert to Stream<Integer>
                IntStream.range(132, 200).boxed())
            .map(String::valueOf) // replaced with method reference 
            .collect(Collectors.toList());
    

    编辑 如果你只想得到一个 IntStream 从给定的输入中,可以将它们连接为:

    IntStream concatenated =  Stream.of(
            IntStream.range(72, 129),
            IntStream.range(132, 200))
        .flatMapToInt(Function.identity());
    

    或者简单地

    IntStream concatenated =  IntStream.concat(
            IntStream.range(72, 129),
            IntStream.range(132, 200));