vendredi 13 mars 2020

If-statement in a stream

Is it possible to use an if statement conidition in my map below?

public Map<LocalDate, Double> avarageTemperatures(LocalDate dateFrom, LocalDate dateTo) {

    Map<LocalDate, Double> temperaturesAverage = weatherData.stream()
            .collect(Collectors.groupingBy(Weather::getDateTime,
                    Collectors.averagingDouble(Weather::getTemperature)));

    System.out.println("average: " + temperaturesAverage);
    return temperaturesAverage;}

I want to only return the dates and temperatureAverage for dates between datefrom and dateTo, which is user input. So I would like to implement an if-statement like

        for (Weather weather : weatherData){
        if(!weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom)){}

where weatherData is an ArrayList containing dates and temperatures. My weather class:

public class Weather {

private LocalDate dateTime;
private LocalTime time;
private double temperature;
private String tag;

public Weather(LocalDate dateTime, LocalTime time, double temperature, String tag) {
    this.dateTime = dateTime;
    this.time = time;
    this.temperature = temperature;
    this.tag = tag;
}

public LocalDate getDateTime() {
    return dateTime;
}


public LocalTime getTime() {
    return time;
}

public double getTemperature() {
    return temperature;
}

public String getTag() {
    return tag;
}}

The dates are of the form 1946-01-15, and temperature of the form -0.3.

Aucun commentaire:

Enregistrer un commentaire