Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create IntStream from Set<Integer>?

I currently do this:

Set<Integer> integers = ... // sourced from elsewhere in code
IntStream intStream = integers.stream().mapToInt(value -> value);

It seems redundant to have to map value to value, to convert the Stream<Integer> to IntStream. Is there a way to do this without that redundant mapToInt(...) section?

like image 564
Steve McLeod Avatar asked Aug 21 '15 10:08

Steve McLeod


1 Answers

No, you have to use .mapToInt(value -> value) or (looks better to me) .mapToInt(Integer::intValue). As Stream is the generic class, it should work for any generic stream element type, thus it's impossible to add something simpler to the API in type-safe manner. Consider, for example, that there's asIntStream() method in Stream interface. It would certainly look better like:

IntStream intStream = integers.stream().asIntStream();

However nothing would stop you to call such method for Stream<String> for example. There's no way in Java to enable calling the method for particular generic parameter only. Thus calling it accidentally on the stream of another type would compile fine, but result in runtime exception which is bad in statically-typed language. However using .mapToInt(value -> value) or .mapToInt(Integer::intValue) you force the type checking: you must supply a function which returns int, so stringStream.mapToInt(value -> value) correctly reports compilation error.

If you really care, you are free to create a static method in your project like this:

public class Streams {
    public static IntStream intStream(Collection<Integer> c) {
        return c.stream().mapToInt(Integer::intValue);
    }
}

And use it like

IntStream intStream = Streams.intStream(integers);
like image 190
Tagir Valeev Avatar answered Sep 17 '22 12:09

Tagir Valeev