Search code examples
javajava-stream

How to cast to ProductDTO from stream?


I have list of lists where each list is [[ID,AMOUNT],[ID,AMOUNT]] Trying to put all this into a list where each element will be Product that i get from DB and description i the amount of products...

The main problem happens when i try to cast back from stream into ProductDTO.

Could be done in a few seconds without using Stream Api, but i have to use only them=(

        List<List<String>> listOfMap = new ArrayList<>(); // Data [[25,1],[13,2],[30,1],[22,1]]

        List<ProductDTO> ordersList = new ArrayList<>();



        listOfMap.forEach(s->ordersList.add(productService.
                getProductById(Long.valueOf(s.get(0))).stream().
                peek(e->e.setDescription(s.get(1)))));


This data inside List<List<String>>
[[25,1],[13,2],[30,1],[22,1]]
Should be this
[PersonDTO,PersonDTO]

the same solution but with loop

    for (int i = 0; i < listOfMap.size(); i++){
        ordersList.add(productService.getProductById(Long.valueOf(listOfMap.get(i).get(0))).orElseThrow());
        ordersList.get(i).setDescription(listOfMap.get(i).get(1));
    }
Required type:
ProductDTO

Provided:
Stream
<org.greenway.backend.dto.ProductDTO>

Solution

  • i dont know productService.getProductById method return what, Optional orList. if Optional,you can use the method flatMap. if List,you can change the methd peek to map Here is the pseudo-code,hope it useful.

        listOfMap.forEach(s->ordersList.add(productService.
                        getProductById(Long.valueOf(s.get(0))).flatMap(e->{ e.setDescription(s.get(1));return e;})));
    
     listOfMap.forEach(s->ordersList.add(productService.
                    getProductById(Long.valueOf(s.get(0))).stream().
                    map(e->{return e.setDescription(s.get(1));}.collect(Collectors.toList()).get(0))));