Java examples for Lambda Stream:Stream
Implement the flatMap function on list<T>, which should be equivalent to list.stream().flatMap(f)
import java.util.ArrayList; import java.util.List; import java.util.function.Function; public class Main { /**/*from w w w. jav a 2s .c o m*/ * Implement the flatMap function on list<T>. The result should be equivalent to * the execution of the code: * * <pre> * list.stream().flatMap(f).collect(Collectors.toList()) ; BUT YOU CANNOT USE * Stream API in this implementation. * * @param list * @param f * a function from T to List<R> * @return a list fo type list<R> */ public static <T, R> List<R> flatMap(List<T> list, Function<? super T, List<R>> f) { // The result should be equivalent to the code: // list.stream().flatMap(f) ; List<R> rlt = new ArrayList<>(); list.forEach(t -> f.apply(t).forEach(rlt::add)); return rlt; } }