Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Stream<Stream<T>> to List<T>

I am new to java 8. I have written following piece of code:

Stream<Stream<POLine>> list = poSearchResponseList.stream().map(poSearchResponse ->
        poSearchResponse.getDeliveryDocumentLines().stream().map(deliveryDocumentLine ->
                POLine.builder()
                        .poLineNumber(deliveryDocumentLine.getPurchaseReferenceLineNumber())
                        .quantity(deliveryDocumentLine.getExpectedQty())
                        .vnpkQty(deliveryDocumentLine.getVnpkQty())
                        .build()));

I want to get

List<POList>

from this right hand expression. Cannot understand how to convert this Stream of stream to a list.

like image 391
Joy Avatar asked Jan 26 '26 15:01

Joy


1 Answers

Using flatMap, it's trivial to convert a Stream<Stream<POLine>> to a Stream<POLine>:

List<POLine> output = 
    list.flatMap(Function.identity())
        .collect(Collectors.toList());

Though it might be simpler to produce a List<POLine> directly:

List<POLine> list = 
    poSearchResponseList.stream()
                        .flatMap(posr -> posr.getDeliveryDocumentLines()
                                             .stream()
                                             .map(dl -> 
                                                 POLine.builder()
                                                       .poLineNumber(dl.getPurchaseReferenceLineNumber())
                                                       .quantity(deliveryDocumentLine.getExpectedQty())
                                                       .vnpkQty(deliveryDocumentLine.getVnpkQty())
                                                       .build()))
                        .collect(Collectors.toList());
like image 155
Eran Avatar answered Jan 28 '26 03:01

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!