I have the following Java 8+ code (on Java 14). I have a (terminal) forEach
call and I am adding each mapped object to a newly created ArrayList
.
Is there a more idiomatic way this could be rewritten using Collectors.toList()
and potentially flatMap
?
public List<SearchSuggestion> suggest() {
List<Watchlist> watchlists = someService.findAll();
List<SearchSuggestion> suggestions = new ArrayList<>();
watchlists.forEach(watchlist -> watchlist.getWatchlistItems()
.forEach(watchlistItem -> {
suggestions.add(mapToSearchSuggestion(watchlistItem.getInstrument()));
})
);
return suggestions;
}
private SearchSuggestion mapToSearchSuggestion(Instrument instrument) {
return SearchSuggestion.builder()
.symbol(instrument.getSymbol())
.build();
}