Java Stream GroupingBy collect in custom object

user2578909 :

I have a Temperature Class

class Temperature {
    double minTemp;
    double maxTemp;
    String city;
    String country;
}

I have another class that maintains a collection of Temperature

class Temperatures {
    List<Temperature> temperatures;
}

I want to group the temperatures by countryName using streams.

What I want is

public Map<String, Temperatures> temperaturesByCountry()

But I am unable to get the Temperatures as map value using stream, what I get is List of Temperature.

My groupingBy implementation is following

Map<String, List<Temperature>> result = this.getTemperatures()
                .stream()
                .collect(Collectors.groupingBy(Temperature::getCountry));

I want to get Map<String, Temperatures> instead of Map<String, List<Temperature>>

How can I achieve this.?

ETO :

Assuming you have constructor Temperatures(List<Temperature> temperatures) this should do the trick:

Map<String, Temperatures> result = 
       this.getTemperatures()
           .stream()
           .collect(groupingBy(Temperature::getCountry, 
                               collectingAndThen(toList(), Temperatures::new)));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36972&siteId=1