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 List
s:
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?
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.
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.
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")));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With