Let's suppose a very normal behavior in development: I have one Collection and need to map this Collection to another object. A flatMap scenario.
Example:
We have some method that must return a Set of Source objetc:
public Set<Source> getSources(String searchText);
Let's figure out one implementation:
public Set<Source> getSources(String searchText) {
HashSet<Source> sources = new HashSet<>();
Set<String> urls = this.crawlerService.getUrls(searchText);
urls.forEach(url -> sources.add(Source.builder().url(url).build()));
return sources;
}
One other implementation with Java Stream:
public Set<Source> getSources(String searchText) {
Set<String> urls = this.crawlerService.getUrls(searchText);
return urls.stream()
.flatMap(e -> Stream.of(Source.builder().url(e).build()))
.collect(Collectors.toSet());
}
I prefer the stream way, but I have some questions: how expensive in performance terms is convert to stream and collect to set? It's acceptable to use Stream this way or it's an overkill? Have some other best way to do this kind of scenario using java Stream?