Java 流 - 将列表排序为列表的 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28064263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java stream - Sort a List to a HashMap of Lists
提问by Bick
Let's say I have a Dog
class.
假设我有一Dog
堂课。
Inside it I have a Map<String,String>
and one of the values is Breed
.
在它里面我有一个Map<String,String>
,其中一个值是Breed
.
public class Dog {
String id;
...
public Map<String,String>
}
I want to get a Map
of List
s:
我想获得Map
的List
S:
HashMap<String, List<Dog>> // breed to a List<Dog>
I'd prefer to use a Stream
rather than iterating it.
我更喜欢使用 aStream
而不是迭代它。
How can I do it?
我该怎么做?
采纳答案by Eran
You can do it with groupingBy
.
你可以用groupingBy
.
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 :
假设您的输入是 a List<Dog>
,则类中的Map
成员Dog
称为map
,并且 Breed 存储为“Breed”键:
List<Dog> dogs = ...
HashMap<String, List<Dog>> map = dogs.stream()
.collect (Collectors.groupingBy(d -> d.map.get("Breed")));
回答by Nestor Milyaev
The great answer above can further be improved by using functional programming notation:
通过使用函数式编程符号可以进一步改进上面的好答案:
List<Dog> dogs = ...
Map<String, List<Dog>> map = dogs.stream()
.collect(Collectors.groupingBy(Dog::getBreed));