在POJO的属性中使用Java Streams是否是一个好的实践?

huangapple go评论67阅读模式
英文:

Is it a good practice to use Java Streams in POJO as attributes

问题

我刚第一次看到这个,我想知道这是不是一个好的做法,还是像往常一样,这取决于情况。

在域中将流(Streams)用作属性,而不是列表(List)。

public class MyDomain {

    Integer id;
    Stream<SubDomain> subDomains;

}
英文:

I just saw this for the first time and I would like to know if this is a good practice or as always it depends.

Using Streams as attributes in the domain instead of a List.

public class MyDomain {

    Integer id;
    Stream&lt;SubDomain&gt; subDomains;

}

答案1

得分: 10

不,这不是一个好的实践。流(Streams)的创建是为了支持对元素流进行函数式操作(详见官方 Javadoc),而不是为了将它们持久化。

在官方的 Javadoc 中还有另一个好的引用:

流与集合在几个方面不同:
没有存储。流不是存储元素的数据结构;相反,它通过计算操作的管道,从诸如数据结构、数组、生成器函数或I/O通道等来源传递元素。

因此,不要将其用作持久化集合。

英文:

No, that isn't a good practice. Streams have been created to support functional-style operations on streams of elements (see official Javadoc) but not to persist them.

The is an other good quote in the official Javadoc:

> Streams differ from collections in several ways:
> No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.

So don't use it as a persistent collection.

答案2

得分: 8

这不是一个好主意,流(stream)只能被消耗(consumed)一次。将其作为对象字段将使得很可能需要多次消耗它。为了能够做到这一点,您需要存储集合类(例如一个 List),并在需要将其内容作为流访问时调用其 stream() 方法。

英文:

This is not a good idea, a stream can be consumed once. Having it as a field in an object will make it likely it is necessary to consume more than once. To be able to do that, you need to store the collection class (eg a List), and call its stream() method when you need to access its contents as a stream.

huangapple
  • 本文由 发表于 2020年10月1日 17:14:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64152321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定