Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two IntStreams?

I want to create a List<String> with the numerical values from 72-129 and 132-200. I thought about using an IntStream and mapping the values to strings and collecting to a list. I used this code:

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

However, if I debug the actual values of strings72to200, I get this:

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

I believe that the Stream.concat() as well as the .map() are causing this, as I do have a working piece of code like this:

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

Note that this piece uses .mapToObj() instead of .map().

So the question is, how can I create a list with these values (note the initial split) via streams (as this seems to be smoother than a loop)? Should I create the full list and remove the unwanted items afterwards (unfeasible on bigger gaps)?

like image 950
XtremeBaumer Avatar asked Feb 04 '23 19:02

XtremeBaumer


2 Answers

You're passing to concat two Stream<IntStream>, which won't work (you want a stream of integers). You need to give it two Stream<Integer>:

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

And just a side note, if you intend to include 129 and 200 in the streams, you should use IntStream.rangeClosed (end is exclusive)

like image 190
ernest_k Avatar answered Feb 06 '23 10:02

ernest_k


You might just be looking for boxed there to get a Stream<Integer> and then concatenate :

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

Edit: If you were to just get an IntStream from the given inputs, you could have concatenated them as:

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

or simply

IntStream concatenated =  IntStream.concat(
        IntStream.range(72, 129),
        IntStream.range(132, 200));
like image 26
Naman Avatar answered Feb 06 '23 10:02

Naman