Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter a list with common string and group to a new list

I have a List<String> which consist of a json string. example below has 5 items in the list. Is there any simple way to extract common class (ex. Biology, Mathematics, History) from the list and group it and create a new List for all the common class.

{"name":"Alex","age":"31","class":"Biology","parents":{"father":"Robert","mother":"Mary"}}
{"name":"John","age":"34","class":"Mathematics","parents":{"father":"Remi","mother":"Maya"}}
{"name":"Rita","age":"27","class":"History","parents":{"father":"Shankar","mother":"Anita"}}
{"name":"Sonia","age":"27","class":"Biology","parents":{"father":"Mathew","mother":"Lucy"}}
{"name":"Caroline","age":"29","class":"Mathematics","parents":{"father":"David","mother":"Christine"}}

expected:

List newList1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"name":"Alex","age":"31","class":"Biology","parents":{"father":"Robert","mother":"Mary"}}
{"name":"Sonia","age":"27","class":"Biology","parents":{"father":"Mathew","mother":"Lucy"}}

List newList2

{"name":"John","age":"34","class":"Mathematics","parents":{"father":"Remi","mother":"Maya"}
{"name":"Caroline","age":"29","class":"Mathematics","parents":{"father":"David","mother":"Christine"}}

List newList3

{"name":"Rita","age":"27","class":"History","parents":{"father":"Shankar","mother":"Anita"}}

>Solution :

  1. Create a DTO representing your JSON structure (e.g. class YourDTO)
  2. Use Jackson’s ObjectMapper to parse your JSON string to instances of the Java class
  3. Use Stream API and groupingBy collector to create a Map<String, List<YourDTO>>, by grouping on the Category of the parsed object
  4. Assign the required categories to separate variables or call .values() on the map to get a List<List<YourDTO>>.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading