Reputation:
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.?
Upvotes: 12
Views: 6152
Reputation: 32036
Alternatively, you could have combined a Map.forEach
with your existing information as:
Map<String, Temperatures> temperaturesByCountry = new HashMap<>();
Map<String, List<Temperature>> result = this.getTemperatures()
.stream()
.collect(Collectors.groupingBy(Temperature::getCountry));
result.forEach((k, v) -> temperaturesByCountry.put(k, new Temperatures(v)));
Upvotes: 2
Reputation: 7299
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)));
Upvotes: 5