4

I am trying to get certain integers, all which I am getting over the stream, however, they are essentially being added to a new stream of integers which I will be using later on.

To populate the new stream of integers, I make multiple IntStreams and then append them to a new one using the IntStream builder, as such:

Is there a better way to approach this:

    IntStream rightSide = IntStream.range(8, this.rows.getSlotAmount()).map(value -> value + 9);
    IntStream leftSide = IntStream.range(0, this.rows.getSlotAmount()).map(value -> value % 9);
    IntStream top = IntStream.range(0, 9);
    IntStream bottom = IntStream.range(this.rows.getSlotAmount() - 9, this.rows.getSlotAmount());

    IntStream.Builder slots = IntStream.builder();

    rightSide.forEach(slots::add);
    leftSide.forEach(slots::add);
    top.forEach(slots::add);
    bottom.forEach(slots::add);

    slots.build().forEach(this::methodReference);
JDC
  • 4,247
  • 5
  • 31
  • 74
slees 2043
  • 55
  • 1
  • 5
  • You could use`IntStream#concat()` but it only accepts 2 Streams.. – Lino Jul 28 '17 at 04:53
  • Would it be better to join all four, and have 2 IntStreams then join those 2 together(essentially having 3 streams altogether) and manipulate the resulting values? – slees 2043 Jul 28 '17 at 04:56
  • You can use `IntStream.concat(IntStream.concat(rightSide, leftSide), IntStream.concat(top, bottom))`. This doesn’t scale with a larger number of streams, so if you have more streams, `Stream.of(…).flatMapToInt(x -> x)` would be better. Another alternative is to forget about creating a single stream at all. In your example, you are calling `forEach(slots::add);` on each stream, just to call `.forEach(this::methodReference);` on the resulting stream. Why not run `.forEach(this::methodReference);` on each of the four streams in the first place… – Holger Jul 28 '17 at 12:10

1 Answers1

7

Whenever seeing multiple streams, I think about flatten. Hope it helps.

Stream.of(rightSide, leftSide, top, bottom).flatMapToInt(x -> x)
Duong Nguyen
  • 830
  • 6
  • 10
  • Yes, one of the solutions I ended up finding. Looks like guava has a similar method to achieve the joining of multiple streams, too. Thanks. – slees 2043 Jul 28 '17 at 05:26