英文:
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<Animal>
into a Map<String, Collection<Animal>>
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<String, Collection<Animal>> collect = animals.stream()
.collect(Collectors.groupingBy(Animal::getSpecies,
Collectors.toCollection(ArrayList::new)));
But Instead of the expected Collection<Animal>
I would suggest to use another type like List<Animal>
:
Map<String, List<Animal>> collect = animals.stream()
.collect(Collectors.groupingBy(Animal::getSpecies));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论