Bill Bill - 4 months ago 14
Java Question

How to map from one container into another w/Java 8 streams?

So, in Clojure, I can just say something like this...

(into [] (map some-function some-collection))


And I get a new vector of my transformed data.

Is there some simple equivalent of
into
for Java 8 streams? For example, I don't see a constructor on
ArrayList
that takes a stream, nor do I see some sort of helper function in
java.util.Collections
, nor the stream interface.

Answer

You can do it using Collectors:

someCollection.stream()
              .map(someFunction)
              .collect(Collectors.toList());

You can do other cool stuff with Collectors, as explained in its javadoc:

 Map<Department, Integer> totalByDept =
     employees.stream()
              .collect(Collectors.groupingBy(Employee::getDepartment,
                                               Collectors.summingInt(Employee::getSalary)));
Comments