ram lou :
I'd like to transform (with Java8) a list of (JSON) data to a hierarchical structure.
Could you please tell me what is the best way to deal with this?
How can I convert an arraylist to a multidimensional map?
The problem is something like converting this:
{
"server": "Manufacturer Co.",
"vehicles": [
{
"year": 2018,
"model": "Ford Explorer (1)",
"category": "4WD"
},
{
"year": 2018,
"model": "Ford Explorer (2)",
"category": "4WD"
},
{
"year": 2017,
"model": "Ford Mustang (3)",
"category": "2WD"
}
{
"year": 2017,
"model": "Ford Mustang 4WD (4)",
"category": "4WD"
}
}
into that
vehicles
-- year 2018
----- category: 4WD
---------- Ford Explorer (1)
---------- Ford Explorer (2)
-- year 2017
----- category: 2WD
---------- Ford Mustang (3)
----- category: 4WD
---------- Ford Mustang (4)
Thanks for your time
Hadi J :
You should use multiple groupingBy
and then use mapping
to collect model property to list.
I'v supposed you have a model something like this:
public class Vehicle {
private int year;
private String model;
private String category;
//other
}
Map<Integer,Map<String,List<String>>> result = vehicles.stream()
.collect(Collectors.groupingBy(Vehicle::getYear,
Collectors.groupingBy(Vehicle::getCategory,
Collectors.mapping(Vehicle::getModel, Collectors.toList()))));