Java Stream GroupingBy collect in custom object
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)));
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)));