Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to collect a stream to two different collections using one line?

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?

like image 814
Mr.WorshipMe Avatar asked Dec 06 '22 19:12

Mr.WorshipMe


1 Answers

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.

like image 120
Acanda Avatar answered May 23 '23 18:05

Acanda