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:
- Create a DTO representing your JSON structure (e.g.
class YourDTO
) - Use Jackson's ObjectMapper to parse your JSON string to instances of the Java class
- Use Stream API and
groupingBy
collector to create aMap<String, List<YourDTO>>
, by grouping on the Category of the parsed object - Assign the required categories to separate variables or call
.values()
on the map to get aList<List<YourDTO>>
.