What are the use cases for IntStream?

use*_*842 1 java lambda

I've written some code that creates a List<Integer> from a Stream<List<Integer>> like so:

List<Integer> abc = stream.flatMap(e -> e.stream()).
    collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

But I'm interested how to use IntStream. I thought I could do

List<Integer> abc = stream.flatMapToInt(e -> e.stream()).
    collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

using flatMapToInt to give me an IntStream that the collector would collect, but I get a compilation error:

Type mismatch: cannot convert from Collector<Object,?,List<Object>> to Supplier<R>
Run Code Online (Sandbox Code Playgroud)

What is an IntStream, how is it different to a regular stream, and when would you use it?

Lou*_*man 5

You more-or-less use IntStream when you have intermediate or terminal operations that don't require boxing, and frequently when you want arithmetic results. For example, you might write

students.stream().mapToInt(Student::getTestScore).average()
Run Code Online (Sandbox Code Playgroud)

Generally, you'd want to use it when your intermediate results are not boxed -- not the case with a List<List<Integer>> and either you're mapping the unboxed result to a boxed thing with mapToObj, or doing something arithmeticky with it like average() here.

除了这个用例可能带来的痛苦之外,它不会给你带来任何好处,它实际上并不关心列表内容是否为Integers;你在这里没有使用任何关于整数的东西。