简体   繁体   中英

Transform a list in another with stream map java 8

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.

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());

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM