How to return the result of a map? Are there any predefined collectors?

Brian Goetz brian.goetz at oracle.com
Fri Feb 22 14:16:53 PST 2013


> The result of a sequence of map operations is a Stream<T>. However I needed
> to cast the functions explicitly as follows
>
> Stream<Integer> doubles =
> Arrays.asList(1,2,3,4).stream().map((Function<Integer, Integer>) n -> n *
> 2).map((Function<Integer, Integer>) n -> n + 1);
>
> Q1. Is there a way to avoid the cast Function<Integer, Integer> here?

Yes -- just don't do it.  Without the cast, it will select the override 
map(ToIntFunction<Integer>), which will get you out of boxed land, and 
return an IntStream.

You can do even better by:

   Streams.intRange(0, 5)  // IntStream
          .map(x -> x*2)   // IntStream
          .map(x -> x+1)   // IntStream

and there's no boxing at all.

> Also I wanted to convert the stream into a List. I understood the way to do
> so is using a collector. Google searches led me to believe there is a
> function toList() which should help. However I couldn't find a method
> "toList" on Stream. Neither could I easily locate it anywhere in the java
> docs.

   .collect(Collectors.toList())

If you have an IntStream and you want to put it into a List<Integer>:

List<Integer> list =
   intStream.boxed()  // Stream<Integer>
            .collect(Collectors.toList());

> Q2. Are there any predefined collectors I could use ? eg. in this case to
> convert a Stream<Int> into a List<Int>

See above -- Collectors.toList() or .toCollection(ctor).

Or, you can use the explicit form of Collect:

   stream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);



More information about the lambda-dev mailing list