Search code examples
javajava-8hashmapjava-streamtreemap

Java- Hash Map - Data Grouping


Is there a way we can group it as per below output

inputData json

    [

 {
    'Car': 'BWM',
    'Country': 'Germany',
    'Amount': 13469,
    'Dateof Purchase':20-08-2020
    
 },
 {
    'Car': 'Audi',
    'Country': 'Germany',
    'Amount': 14469,
    'Dateof Purchase':10-01-2020

 }
 {
    'Car': 'Telsa',
    'Country': 'American',
    'Amount': 11449,
    'Dateof Purchase':15-12-2020

 }
]

output

Germany -27938  <-- Total Amount
    BWM : 13469 
    Audi: 14469

American-11449 <-- Total Amount
    Telsa 11449

I tried using the below code, but only able to get Car Country Total

        Map<String, Integer> Total_Vech = listData.stream()
            .collect(Collectors.groupingBy(Vech::getbycountry,
                    Collectors.summingInt(Vech::getsAmount)));

Any help would be helpful !!!


Solution

  • You'll need a custom data structure:

    class CountryStats {
        private int amount;
        private Map<String, Integer> cars = new HashMap<>();
    
        void addCar(String car, int amount) {
            this.amount += amount;
            this.cars.merge(car, amount, Integer::sum);
        }
    
        CountryStats merge(CountryStats country) {
            country.cars.forEach(this::addCar);
            return this;
        }
    }
    

    Then you can collect them like this:

    Map<String, CountryStats> statsByCountry = data.stream().collect(
            Collectors.groupingBy(data -> data.getCountry(), Collector.of(
                    CountryStats::new,
                    (stats, data) -> stats.addCar(data.getCar(), data.getAmount()),
                    CountryStats::merge)));