Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream - Sort a List to a HashMap of Lists

Let's say I have a Dog class.

Inside it I have a Map<String,String> and one of the values is Breed.

public class Dog {     String id;     ...     public Map<String,String> } 

I want to get a Map of Lists:

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

I'd prefer to use a Stream rather than iterating it.

How can I do it?

like image 238
Bick Avatar asked Jan 21 '15 09:01

Bick


People also ask

How do I sort a List in streams?

Stream sorted() in Java Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.

Can you put a List in a HashMap?

Among those, HashMap is a collection of key-value pairs that maps a unique key to a value. Also, a List holds a sequence of objects of the same type. We can put either simple values or complex objects in these data structures.


2 Answers

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"))); 
like image 117
Eran Avatar answered Oct 03 '22 10:10

Eran


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));  
like image 41
Nestor Milyaev Avatar answered Oct 03 '22 12:10

Nestor Milyaev