I have the following code: (simplified for bravity)
public void search(Predicate<String> predicate, Elements elements)
{
List<SearchResult> searchResults = elements.stream()
.filter(element -> predicate.test(element.ownText()))
.map(element -> new SearchResult(element.ownText(), element.baseUri(),element.tagName()))
.collect(Collectors.toList());
}
But now, I want to have another list which would contain all filtered elements without the mapping. Is it possible to do that with a stream, or should I change to a foreach loop for that?
You can collect the elements after filtering and then use this list to map the elements to search results:
public void search(Predicate<String> predicate, Elements elements) {
List<Element> filteredElements =
elements.stream()
.filter(element -> predicate.test(element.ownText()))
.collect(Collectors.toList());
List<SearchResult> searchResults =
filteredElements.stream()
.map(element -> new SearchResult(element.ownText(),element.baseUri(),element.tagName()))
.collect(Collectors.toList());
}
This won't take more time than the solutions of the other answers but doesn't have side effects, is thread safe as well as easy to read and understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With