Home > database >  How to filter a list with common string and group to a new list
How to filter a list with common string and group to a new list

Time:10-02

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

{"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"}}

CodePudding user response:

  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>>.
  • Related