Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a List to multidimensional Map

Tags:

java

java-8

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

like image 934
ram lou Avatar asked May 23 '26 02:05

ram lou


2 Answers

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()))));
like image 53
Hadi J Avatar answered May 25 '26 15:05

Hadi J


There are two approaches. First one would be to create a Map with key Year of Maps with key Category of Models. Iterate through all vehicles, create an entry for a year if it doesn't exist, add a category if it doesn't exist and add a model if it doesn't exist.

A bit more elegant approach would be to use an in-memory database. Create a table vehicles with columns year, category and model and then query it with:

select year, category, model
from   vehicle
order by year, category;
like image 22
Boris Pavlović Avatar answered May 25 '26 17:05

Boris Pavlović