I would like to group a list of maps by value and insert(merge) as grouped lists in certain conditions. Group by a value "yr" and merge "tag" by the same "category" then sum up the "price" them together, then after order in descending order by "price"
List<Grocery> groceryList = new ArrayList<>();
Grocery grocery = new Grocery();
List<HahsMap<String, Object>> tagList = new ArrayList<>();
HashMap<String, Object> tagMap = new HashMap<>();
## feeding data example
tagMap.put("category", "A");
tagMap.put("name", "Apple");
tagMap.put("price", 10);
tagList.add(tagMap);
grocery.setYr(String yr);
grocery.setTag(List<Hashmap<String, Object>> tagList);
groceryList.add(grocery);
This is an example of a list of maps.
List<Grocery> groceryList =
[
{
"yr": "2021",
"tag": [
{
"Category": "A",
"Name": "Apple",
"Price": 10
}
]
},
{
"yr": "2021",
"tag": [
{
"Category": "A",
"Name": "Apple",
"Price": 10
}
]
},
{
"yr": "2021",
"tag": [
{
"Category": "B",
"Name": "Banana",
"Price": 5
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "A",
"Name": "Apple",
"Price": 10
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "B",
"Name": "Banana",
"Price": 30
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "C",
"Name": "Candy",
"Price": 10
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "C",
"Name": "Candy",
"Price": 30
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "A",
"Name": "Apple",
"Price": 10
}
]
}
]
This is the sample output I want to get
List<Grocery> result =
[
{
"yr": "2021",
"tag": [
{
"Category": "A",
"Name": "Apple",
"Price": 20
},
{
"Category": "B",
"Name": "Banada",
"Price": 5
}
]
},
{
"yr": "2020",
"tag": [
{
"Category": "C",
"Name": "Candy",
"Price": 40
},
{
"Category": "B",
"Name": "Banada",
"Price": 30
},
{
"Category": "A",
"Name": "Apple",
"Price": 20
}
]
}
]
I know this is tricky to combine all the condition into one, could anyone help me out?? It will be really appreciated if at least I could have some ideas what to do about this..
I tried to group them in a 'yr' first, and try to find the values to map out then sort them out with the same 'category' then sum up.. but i have no clue on sorting them and merge them together with summed up 'price'..
Thanks in advance!!