Java 8 idiomatic way to apply Lambda to a list returning another list?

What is the most idiomatic mechanism for applying lambda to each element in a list, returning a list of results?

For instance:

List<Integer> listA = ... imagine some initialization code here ... List<Integer> listB = listA.apply(a -> a * a); // pseudo-code (there is no "apply") /* listB now contains the square of every value in listA */ 

I checked the javadocs API and also looked at the Apache Commons but found nothing.

+5
source share
4 answers

To add @Eran to the answer, I have a helper method:

 public static <T, R> List<R> apply(Collection<T> coll, Function<? super T, ? extends R> mapper) { return coll.stream().map(mapper).collect(Collectors.toList()); } 

can be used as:

 List<Integer> listB = apply(listA, a -> a * a); 

(Note: Java 1.8 or higher is required.)

+10
source

You can use Stream with map and collect :

 listB = listA.stream() .map (a -> a*a) .collect (Collectors.toList()); 
+21
source

The most standard way is to simply collect them at the end:

 List<Integer> listA = ... imagine some initialization code here ... List<String> listB = listA.stream() .map(a -> a.toString()) .collect(Collectors.toList()); 

Notice how the map function introduces a conversion from, in this case, Integer to String, and the returned list is of type List<String> . The conversion is done using the map, and the List is generated by the collector.

+3
source

If you do not mind using a third-party library, you can use powerful new collections.

 // import javaslang.collection.*; listB = listA.map(f); 

These Java 8 collections are immutable and can be compared to those of Scala and Clojure. Please read here .

Btw - there is also syntactic sugar for for-loops:

 // import static javaslang.API.*; // import javaslang.collection.Stream; Stream<R> result = For(iterable1, ..., iterableN).yield((e1, ..., eN) -> ...); 

Disclaimer: I am the creator of Javaslang.

+1
source

Source: https://habr.com/ru/post/1204057/


All Articles