将一个集合分割成多个以流方式分组在映射中的集合。

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

Splitting a Collection into multipe collections grouped in a map using streams

问题

好的,以下是您提供的内容的中文翻译:

假设我有一个类

public class Animal {
 String name;
 String species;
}

我想知道是否有一种使用流(Stream)的好方法,将一个 Collection<Animal> 拆分成一个 Map<String, Collection<Animal>>,按物种(species)对不同的动物进行分组。

我可以用老方法来做,但我想在这里使用流可能会更好。我的主要问题是我不知道如何“边遍历边创建列表”。

英文:

Let's say I have a class

public class Animal {
 String name;
 String species;
}

I would like to know if there is a good way using stream to split a Collection&lt;Animal&gt; into a Map&lt;String, Collection&lt;Animal&gt;&gt; grouping different animals by species.

I can do it the old way but I suppose there is an use for streams in there. My main problem is that I don't know how to "create a list on the go".

答案1

得分: 1

你是否想要类似这样的内容:

Map<String, Collection<Animal>> collect = animals.stream()
        .collect(Collectors.groupingBy(Animal::getSpecies, 
                Collectors.toCollection(ArrayList::new)));

但是我建议您使用另一种类型`List<Animal>`,而不是预期的 `Collection<Animal>`:

```java
Map<String, List<Animal>> collect = animals.stream()
        .collect(Collectors.groupingBy(Animal::getSpecies));
英文:

Are you looking to something like this:

Map&lt;String, Collection&lt;Animal&gt;&gt; collect = animals.stream()
        .collect(Collectors.groupingBy(Animal::getSpecies, 
                Collectors.toCollection(ArrayList::new)));

But Instead of the expected Collection&lt;Animal&gt; I would suggest to use another type like List&lt;Animal&gt;:

Map&lt;String, List&lt;Animal&gt;&gt; collect = animals.stream()
        .collect(Collectors.groupingBy(Animal::getSpecies));

huangapple
  • 本文由 发表于 2020年4月7日 01:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61065818.html
匿名

发表评论

匿名网友

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

确定