Issue
I have this foreach
that parses some class to another:
public static List<MyClassParsed> getMyParsed(List<MyClassResponse> responses) {
List<MyClassParsed> parses = new ArrayList<>();
for (MyClassResponse response : responses) {
var parse = MyClassParsed.builder()
.id(response.getId())
.name(response.getName())
.build();
parses.add(parse);
}
return detalhes;
}
I mean, can I do this using something like responses.stream().foreach(...)
?
Solution
You're transforming a list to a list of objects derived from elements of that list, so map
looks like a good solution.
public static List<MyClassParsed> getMyParsed(List<MyClassResponse> responses) {
return responses.stream()
.map(r ->
MyClassParsed
.builder()
.id(r.getId())
.name(r.getName())
.build())
.collect(Collectors.toList());
}
Answered By - Federico klez Culloca
Answer Checked By - Cary Denson (JavaFixing Admin)