Input: I have a list of Map (Key - Value pairs) and grouping keys
e.g.List<Map<String,String>> inputData json
[
{
'a': 'German',
'b': 'Audi',
'e': 'T3'
},
{
'a': 'German',
'b': 'BMW',
'c': 'T6'
},
{
'a': 'American',
'b': 'Tesla',
'c': 'T6'
}
]
and groupingKeys= a and b
For Grouping key a -> I will create two buckets, one for German and other American and in each bucket I will again create bucket for value of b, check following
I want to produce following: Map<String, Map<String, List<Map>> - the nesting of maps == number of grouping keys, here it's 2
{
German: {
Audi: [
{
'a': 'German',
'b': 'Audi',
'e': 'T3'
}
],
BMW: [
{
'a': 'German',
'b': 'BMW',
'c': 'T6'
}
]
},
American: {
Tesla: [
{
'a': 'American',
'b': 'Tesla',
'c': 'T6'
}
]
}
}
Things I tried:
inputData.stream().collect(Collectors.groupingBy(mapItem -> this.constructGroupingKey(groupingKeys, mapItem)));
//constructGroupingKey - this joins the values of of given grouping keys
This way I can construct concatenated key e.g German-Audi OR German-BMW and save the matching item against it but it's not what I want exactly.
As @Naman said here about concrete class - following makes it one liner but I can't make assumptions about data, it's of type Map
Map<String, Map<String, List<ConcreteClass>>> output = inputData.stream().collect(Collectors.groupingBy(ConcreteClass::getCountry, Collectors.groupingBy(ConcreteClass::getCarType)));
Would appreciate other ideas, thanks. I am also curious if I can derive grouping based on given data without specification of grouping keys.
Input is of dynamic nature, key and value are defined by the input