Reputation: 45
I want to create a list of ErroDto based on a list of FieldError using stream and another options from java 8. I had this with forEach but I want with stream and map:
fieldErrors.stream()
.forEach(e -> errosDto.add(new ErroDto(e.getField(), e.getDefaultMessage())));
I try like this below but I think its wrong because I'm modifying the second list inside the map:
fieldErrors.stream()
.map(e -> errosDto.add(new ErroDto(e.getField(), e.getDefaultMessage())));
Then I want to map and collect as a list.
Upvotes: 0
Views: 461
Reputation: 207006
The lambda expression that you pass to the map()
method takes the input object and returns the output object. You should not add it to the list inside the map()
method itself. Collect the stream that comes out of map()
into a List<ErroDto>
:
List<ErroDto> errosDto = fieldErrors.stream()
.map(e -> new ErroDto(e.getField(), e.getDefaultMessage()))
.collect(Collectors.toList());
Upvotes: 0
Reputation: 394146
map
should only transform each FieldError
instance to an ErroDto
instance.
Use collect
to collect all the ErroDto
instances into a List
:
List<ErroDto> errosDto =
fieldErrors.stream()
.map(e -> new ErroDto(e.getField(), e.getDefaultMessage()))
.collect(Collectors.toList());
Upvotes: 2