是否可以使用一行将流收集到两个不同的集合中? [英] Is it possible to collect a stream to two different collections using one line?

查看:66
本文介绍了是否可以使用一行将流收集到两个不同的集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:(为了简洁而简化)

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());
}

但是现在,我想要另一个包含所有已过滤元素的列表映射。
是否可以使用流来实现,或者我应该更改为foreach循环?

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.

这篇关于是否可以使用一行将流收集到两个不同的集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆