收集方法的返回值作为List

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

Collect method return as List<CustomObject>

问题

我正在尝试收集方法返回的对象列表。

例如,如果我有一个方法如下:

  public Person doSomething() {
          //定义部分
  }

我想这样收集它:

List<Person> persons = call doSomething()

我可以像这样做:

List<Person> persons = new ArrayList<>();
for(int i = 0; i < length; i++) {
       persons.add(doSomething());
}

其中 length 可以是一个常量和独立的属性,例如 例如 5

只是想知道是否有更好的方法可以使用流来实现这个。

英文:

I am trying to collect the method return as list of Object.

i.e. If I have a method like

  public Person doSomething() {
          //definition
  }

I want to collect it as

List&lt;Person&gt; persons = call doSomething()

I can do it something like this

List&lt;Person&gt; persons = new ArrayList&lt;&gt;();
for(int i = 0; i &lt; length; i++) {
       persons.add(doSomething());
}

Where length can be constant and independent attribute e.g. 5

Just wondering if there is a better way of doing this with streams

答案1

得分: 1

以下是您要的翻译:

用流进行此操作的最简单方法是

List<Person> = Stream.generate(() -> doSomething()).limit(length).collect(toList());

您是否认为这样做更好,这是一个品味的问题。

英文:

The easiest way to do it with streams is

List&lt;Person&gt; = Stream.generate(() -&gt; doSomething()).limit(length).collect(toList());

Whether or not you consider this "better" is a matter of taste.

huangapple
  • 本文由 发表于 2020年9月9日 03:15:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63800241.html
匿名

发表评论

匿名网友

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

确定