Search code examples
javaspring-bootforeach

Iterating using ForEach in Spring -boot


I'm trying to iterate over a repository of database table and once there, access one of the row to finally retrieve the information i need. Thus I first went to my repository over all those elements in the database, applied findAll() method; then being there I used stream().foreach(), which eventually positioned me inside each item being able to retrieve any kind of information, like accessing its lists and other things. But that throws an exception

Required type:Object
Provided:void

here is the function :

public ResponseEntity<Map<String, Object>> allshots(Authentication authentication) {
        Map<String, Object> dto = new HashMap<>();



        dto.put("player_shots_detail", playerCrabRepository.findAll().stream().forEach(playerCrab -> {  playerCrab.getDiceCrabList().stream()
        .map(diceCrab -> makeDiceCrabMiniDto(diceCrab)).collect(Collectors.toList());}));


        return new ResponseEntity<>(dto, HttpStatus.CREATED);
    }

enter image description here

Does that mean I should return something instead of void? I appreciate any help, and thanks in advance


Solution

  • forEach return void but dto.put requird an object. try replace forEach with map

    dto.put("player_shots_detail", playerCrabRepository.findAll().stream().map(playerCrab -> playerCrab.getDiceCrabList()).flatMap(diceCrab -> makeDiceCrabMiniDto(diceCrab)).collect(Collectors.toList()));