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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:33:10  来源:igfitidea点击:

Java stream - Sort a List to a HashMap of Lists

javajava-8hashmapjava-stream

提问by Bick

Let's say I have a Dogclass.

假设我有一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 Mapof Lists:

我想获得MapListS:

HashMap<String, List<Dog>> // breed to a List<Dog>

I'd prefer to use a Streamrather 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 Mapmember inside the Dogclass 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));