Search code examples
javaspringlistspring-bootdto

Iterate through a list of ids, find other attributes on repo and set them into another list


I have a function that accepts List id as a @RequestBody parameter.

I need to find each id's other variables (message,date,noofp), set them in a list of DTO objects.

public class DataDTO {
        private long id;

    private String message;

    private Date date;

    private String noofp;

    private String meaningofp;
}
List<DataDTO> rpaDataList = new ArrayList<>();
        
//this part is where I am confused
         id.forEach(x-> {
            repository.findById(x).map( rpa -> {
            ??????????
            })  
        });
        
return repository.saveAll(rpaDataList);

How can i do it ?

The logic in my head is that I need to iterarte through list of ids, find each id in repository and get other informations. Set them in a DTO object, put these objects into a list and use saveAll method.

Can't seem to put it on code.


Solution

  • You can achieve that by using java streams like this

    List<DataDTO> rpaDataList = id.stream().map(x -> repository.findById(x)).filter(Optional::isPresent).map(Optional::get).toList();
    repository.saveAll(rpaDataList);