流式传输到新集合的集合 [英] Collection to stream to a new collection

查看:88
本文介绍了流式传输到新集合的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最无痛的方式来过滤集合。我在想类似

I'm looking for the most pain free way to filter a collection. I'm thinking something like

Collection<?> foo = existingCollection.stream().filter( ... ). ...

但我不确定如何最好从过滤器转到返回或填充另一个集合。大多数例子似乎都像在这里你可以打印。可能有一个我缺少的构造函数或输出方法。

But I'm not sure how is best to go from the filter, to returning or populating another collection. Most examples seem to be like "and here you can print". Possible there's a constructor, or output method that I'm missing.

推荐答案

大多数示例都避免将结果存储到一个集合。这不是推荐的编程方式。您已经有一个集合,提供源数据和集合的那个就没有用了。您希望对其执行某些操作,因此理想情况是使用流执行操作并跳过将数据存储在中间集合中。这是大多数示例尝试建议的内容。

There’s a reason why most examples avoid storing the result into a Collection. It’s not the recommended way of programming. You already have a Collection, the one providing the source data and collections are of no use on it’s own. You want to perform certain operations on it so the ideal case is to perform the operation using the stream and skip storing the data in an intermediate Collection. This is what most examples try to suggest.

当然,有很多现有的API使用集合 s总会有。所以 Stream API提供了不同的方法来处理 Collection 的需求。

Of course, there are a lot of existing APIs working with Collections and there always will be. So the Stream API offers different ways to handle the demand for a Collection.


  • 获取一个任意列表实现保持结果:

List<T> results = l.stream().filter(…).collect(Collectors.toList());


  • 获取任意设置实施保持结果:

    Set<T> results = l.stream().filter(…).collect(Collectors.toSet());
    


  • 获取特定的集合

    ArrayList<T> results =
      l.stream().filter(…).collect(Collectors.toCollection(ArrayList::new));
    


  • 添加到现有集合

    l.stream().filter(…).forEach(existing::add);
    


  • 创建数组:

  • Create an array:

    String[] array=l.stream().filter(…).toArray(String[]::new);
    


  • 使用数组创建具有特定特定行为的列表(可变,固定大小) :

  • Use the array to create a list with a specific specific behavior (mutable, fixed size):

    List<String> al=Arrays.asList(l.stream().filter(…).toArray(String[]::new));
    


  • 允许支持并行的流添加到临时本地列表并在之后加入它们:

  • Allow a parallel capable stream to add to temporary local lists and join them afterwards:

    List<T> results
      = l.stream().filter(…).collect(ArrayList::new, List::add, List::addAll);
    

    (注意:这与 Collectors.toList()<如何密切相关/ code>目前已实现,但这是一个实现细节,即无法保证 toList()收集器的未来实现仍将返回 ArrayList

    (Note: this is closely related to how Collectors.toList() is currently implemented, but that’s an implementation detail, i.e. there is no guarantee that future implementations of the toList() collectors will still return an ArrayList)

    这篇关于流式传输到新集合的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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