12

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.?

Naman
  • 27,789
  • 26
  • 218
  • 353
  • Could you tell me please the logic for class Temperatures ? Thank you – Echoinacup Jan 10 '19 at 10:10
  • @Echoinacup Temperatures class contains List of Temperature and some other functions having an average, max and min temperatures. This contains a list so that we can group this easily on countries and cities. –  Jan 10 '19 at 10:21
  • @HammadNaeem thank you:) – Echoinacup Jan 10 '19 at 10:23

2 Answers2

5

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)));
ETO
  • 6,970
  • 1
  • 20
  • 37
2

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)));
Naman
  • 27,789
  • 26
  • 218
  • 353