Java 8 map Integer stream to <T> stream

Viewed 777

I am a complete noob in Java 8 features and I am trying to generate a stream of Double objects as a result of processing a stream of Integers, something like this:

IntStream.range(0, 10).forEach(integer -> 50.0);

So I end up with a stream that looks like:

{50.0, 50.0, ... 50.0}

Now, I know forEach doesn't work like that and that this specific case can be solved in other simpler ways, but it's just for the sake of exposition.

Basically, what I am looking for is similar to a forEach except that it expects a return value for each element and is able to produce a stream too.

3 Answers

Generally speaking, the type of operation you're talking about is a map operation: you want to apply a function to each element of a list and return a new list of those results. Here is an example which converts a stream of integers into a custom class and then collects them into a List:

IntStream.range(1, 10)
    .mapToObj(n -> new MyClass(n))
    .collect(Collectors.toList());

// Alternatively - using a method reference 
IntStream.range(1, 10)
    .mapToObj(MyClass::new)
    .collect(Collectors.toList());

// Alternatively - convert from a stream of primitive ints to a stream 
// of Integer objects (i.e. boxed ints) first so we can use methods not
// available on the IntStream object
IntStream.range(1, 10).boxed()
    .map(MyClass::new)
    .collect(Collectors.toList());

As has been mentioned in another answer, you can also use the mapToDouble method for the specific case you mentioned.

You may use map helper function on your integer stream to do to. Check out this code below.

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MapTest {
    public static void main(String[] args) {
        System.out.println(IntStream.range(0, 10).mapToDouble(number -> 50.0).boxed().collect(Collectors.toList()));
    }
}

You can use Stream.generate instead of Stream.range. This is more appropriate for your case, because you don't use values from range:

List<Double> collect = Stream.generate(() -> Double.valueOf(50.0))
                             .limit(10).collect(Collectors.toList());
Related