'how can i iterate through a Stream of Integers and convert into a List of Integer?

relatively new to java and am looking into Streams

I was wondering how I can convert a Stream of Integers based on conditions.

For example, my stream will look something like 1,2,3,4,5 and I want to iterate and check if the next number is 3. If it is, i will add 1, else i will return 0. Thereafter, convert it into a List of Integers which will look like: [0,3,0,0,0]

What i currently have is something like this:

List<Integer> lst = new List.of(1,2,3,4,5);
Stream<Integer> strlst = lst.stream();
strlst.forEach(x -> {if (x.get(x+1).equals(3)) { return x + 1 } else {return 0} });
strlst.toList();


Solution 1:[1]

Here is one way. It uses a nested ternary construct.
a ? b : c says if a is true, do b else do c.

  • stream some indices to reference the list
  • if the index is the last one, put a 0 on the stream
  • otherwise process as required.
List<Integer> list = List.of(1, 2, 3, 4, 5);

List<Integer> result = IntStream.range(0, list.size())
        .map(i -> i == list.size()-1 ? 0 : list.get(i + 1) == 3 ? list.get(i) + 1 : 0)
        .boxed()
        .toList()

prints

[0, 3, 0, 0, 0]

Note: a 3 as the first number in the stream does not have any effect since there is no prior number to increment.

I was wondering how I can convert a Stream of Integers based on conditions.

You should also take a look at Stream.mapMulti

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1