Java stream - Sort a List to a HashMap of Lists

后端 未结 2 1688
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 02:14

Let\'s say I have a Dog class.

Inside it I have a Map and one of the values is Breed.

public         


        
相关标签:
2条回答
  • 2021-01-31 02:55

    The great answer above can further be improved by method reference notation:

    List<Dog> dogs = ...
    Map<String, List<Dog>> map = dogs.stream()
         .collect(Collectors.groupingBy(Dog::getBreed)); 
    
    0 讨论(0)
  • 2021-01-31 03:03

    You can do it with 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 :

    List<Dog> dogs = ...
    Map<String, List<Dog>> map = dogs.stream()
         .collect(Collectors.groupingBy(d -> d.map.get("Breed")));
    
    0 讨论(0)
提交回复
热议问题