Nuñito de la Calzada :
I have this object:
public class MenuPriceByDay implements Serializable {
private BigDecimal avgPrice;
private BigDecimal minPrice;
private BigDecimal maxPrice;
private Date updateDate;
..
}
and this other one:
public class Statistics {
double min;
double max;
double average;
public Statistics() {
super();
}
public Statistics(double min, double max, double average) {
super();
this.min = min;
this.max = max;
this.average = average;
}
}
and also a list of prices:
List<MenuPriceByDay> prices = new ArrayList<MenuPriceByDay>();
that I want to convert to a map:
Map<LocalDate, Statistics> last30DPerDay =
prices
.stream()
.collect(Collectors.toMap(MenuPriceByDay::getUpdateDate, p -> new Statistics( p.getAvgPrice().doubleValue(),
p.getMaxPrice().doubleValue(),
p.getMinPrice().doubleValue())));
but I got a compilation problem:
Type mismatch: cannot convert from Map<Date,Object> to
Map<LocalDate,Statistics>
YCF_L :
UpdateDate
is of type Date
and you try to collect as LocalDate
, so you just need to convert the Date
to LocalDate
:
Map<LocalDate, Statistics> collect = prices.stream()
.collect(Collectors.toMap(m -> m.getUpdateDate()
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate(),
p -> new Statistics(p.getAvgPrice().doubleValue(),
p.getMaxPrice().doubleValue(),
p.getMinPrice().doubleValue())
));
More details about Convert Date to LocalDate or LocalDateTime and Back
Or you can create a method instead like so :
public LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
and your code can be :
Map<LocalDate, Statistics> collect = prices.stream()
.collect(Collectors.toMap(
m -> this.convertToLocalDateViaInstant(m.getUpdateDate()),
p -> new Statistics(p.getAvgPrice().doubleValue(),
p.getMaxPrice().doubleValue(),
p.getMinPrice().doubleValue())
));
Better solution
the best solution is Just to change updateDate
type to LocalDate
:
private LocalDate updateDate;
and you can just use your code