我应该返回一个集合还是流? [英] Should I return a Collection or a Stream?

查看:136
本文介绍了我应该返回一个集合还是流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法返回一个只读视图到成员列表:

Suppose I have a method that returns a read-only view into a member list:

class Team
{
    private List<Player> players = new ArrayList<>();

    // ...

    public List<Player> getPlayers()
    {
        return Collections.unmodifiableList(players);
    }
}

进一步假设所有客户端都迭代列表一次,立即。也许把玩家变成一个JList或者什么东西。

Further suppose that all the client does is iterate over the list once, immediately. Maybe to put the players into a JList or something. The client does not store a reference to the list for later inspection!

在这种情况下,我应该返回一个流吗?

Given this common scenario, should I return a stream instead?

    public Stream<Player> getPlayers()
    {
        return players.stream();
    }

还是在Java中返回一个非惯用的流?是否设计的流总是在它们创建的同一个表达式中终止?

Or is returning a stream non-idiomatic in Java? Were streams designed to always be "terminated" inside the same expression they were created in?

推荐答案

这取决于。这取决于返回的集合将有多大。这取决于结果是否随时间而变化,以及返回结果的一致性有多重要。这取决于用户如何可能使用答案。

The answer is, as always, "it depends". It depends on how big the returned collection will be. It depends on whether the result changes over time, and how important consistency of the returned result is. And it depends very much on how the user is likely to use the answer.

首先,请注意,您始终可以从Stream中获取集合,反之亦然:

First, note that you can always get a Collection from a Stream, and vice versa:

// If API returns Collection, convert with stream()
getFoo().stream()...

// If API returns Stream, use collect()
Collection<T> c = getFooStream().collect(toList());

所以问题是,这对您的呼叫者更有用。

So the question is, which is more useful to your callers.

如果结果可能是无限的,则只有一个选择:Stream。

If your result might be infinite, there's only one choice: Stream.

大,你可能更喜欢Stream,因为可能没有任何价值实现它一次,这样做可能会产生显着的堆压力。

If your result might be very large, you probably prefer Stream, since there may not be any value in materializing it all at once, and doing so could create significant heap pressure.

如果所有的调用者要做的是迭代它(搜索,过滤器,聚合),你应该喜欢Stream,因为Stream已经有这些内置的,没有必要实现一个集合(特别是如果用户可能不处理整个结果)。是一个很常见的情况。

If all the caller is going to do is iterate through it (search, filter, aggregate), you should prefer Stream, since Stream has these built-in already and there's no need to materialize a collection (especially if the user might not process the whole result.) This is a very common case.

即使你知道用户会多次迭代它或者保留它,你仍然可能想返回一个流,而不是简单的事实,无论集合你选择把它(例如,ArrayList)可能不是他们想要的形式,然后调用者必须复制它。如果你返回一个流,他们可以收集(toCollection(工厂)),并得到它的形式他们想要的。

Even if you know that the user will iterate it multiple times or otherwise keep it around, you still may want to return a Stream instead, for the simple fact that whatever Collection you choose to put it in (e.g., ArrayList) may not be the form they want, and then the caller has to copy it anyway. if you return a stream, they can do collect(toCollection(factory)) and get it in exactly the form they want.

上面的喜欢Stream案例大多来源于Stream更灵活的事实;你可以后期绑定到如何使用它,而不会产生实现它到一个集合的成本和约束。

The above "prefer Stream" cases mostly derive from the fact that Stream is more flexible; you can late-bind to how you use it without incurring the costs and constraints of materializing it to a Collection.

您必须返回集合的一种情况是存在强一致性要求时,您必须生成移动目标的一致性快照。然后,你会想要将元素放入一个不会改变的集合。

The one case where you must return a Collection is when there are strong consistency requirements, and you have to produce a consistent snapshot of a moving target. Then, you will want put the elements into a collection that will not change.

所以我会说,大多数时候,Stream是正确的答案 - 更灵活,它不强加通常不必要的物化成本,并且可以很容易地变成你的选择的集合,如果需要。但有时候,你可能需要返回一个集合(比如说,由于强一致性要求),或者你可能想返回Collection,因为你知道用户将如何使用它,知道这是他们最方便的事情。

So I would say that most of the time, Stream is the right answer -- it is more flexible, it doesn't impose usually-unnecessary materialization costs, and can be easily turned into the Collection of your choice if needed. But sometimes, you may have to return a Collection (say, due to strong consistency requirements), or you may want to return Collection because you know how the user will be using it and know this is the most convenient thing for them.

这篇关于我应该返回一个集合还是流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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