Conversion of loop into Lambda expression in java8

Chammu :

I need help in converting code into lambda expression.

I am able to convert the below code into lambda expression

private final List<Envelope> toPersist; //it gets populated
final List<Request> persistables = new ArrayList<>(); //Request is an entity class
for (Envelope envelope : this.toPersist) { //
    Request requests = persistable(envelope);
    persistables.add(requests);
}

to below lambda expression , which is working fine.

final List<Request> persistables = this.toPersist.stream().map(this::persistable).collect(toList());

(working fine).

But I am not able to convert for the below code which contains List.

final List<Annotation> annotations = new ArrayList<>(); //Annotation is an entity class
for (Envelope envelope : this.toPersist) {
   List<Annotation> annotationList = annotationsPersistable(envelope);
   annotations.addAll(annotationList);
}

Kindly help in converting the above code into a lambda expression.

Andronicus :

You can flatMap it:

List<Annotation> annotations = this.toPersist.stream()
    .flatMap(envelope -> annotationsPersistable(envelope).stream())
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169591&siteId=1