Java流-将列表排序到列表的HashMap [英] Java stream - Sort a List to a HashMap of Lists
本文介绍了Java流-将列表排序到列表的HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说我有一个Dog
类.
在其中,我有一个Map<String,String>
,其中一个值是Breed
.
Inside it I have a Map<String,String>
and one of the values is Breed
.
public class Dog {
String id;
...
public Map<String,String>
}
我想获得List
的Map
:
HashMap<String, List<Dog>> // breed to a List<Dog>
我宁愿使用Stream
而不是对其进行迭代.
I'd prefer to use a Stream
rather than iterating it.
我该怎么办?
推荐答案
您可以使用groupingBy
来实现.
假设您的输入是List<Dog>
,在Dog
类内的Map
成员称为map
,并且将品种存储为品种".密钥:
Assuming that your input is a List<Dog>
, the Map
member inside the Dog
class is called map
, and the Breed is stored for the "Breed" key :
List<Dog> dogs = ...
Map<String, List<Dog>> map = dogs.stream()
.collect(Collectors.groupingBy(d -> d.map.get("Breed")));
这篇关于Java流-将列表排序到列表的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文