Convert a list of objects to a map of key and list of objects in Java

 Many times we have a list of objects and we want to group them by a specific field of the object. For example, we have a group of Person objects and we want to find all Person residing in a particular country. 

The easiest way to do this is by converting the list of Person objects into a Map with country as the key and List of Person objects that reside in that country as value.

Java 8 stream comes in very handy to solving this problem.

Suppose we have person object as below.

We can use a very simple Java stream code to convert a List of objects to a Map of Lists.


Above code can be verified using below test:


0 comments:

Post a Comment