gpt4 book ai didi

Java8 收集 map

转载 作者:行者123 更新时间:2023-11-30 06:41:33 27 4
gpt4 key购买 nike

我有这个对象:

public class MenuPriceByDay implements Serializable {

private BigDecimal avgPrice;
private BigDecimal minPrice;
private BigDecimal maxPrice;
private Date updateDate;

..
}

还有这个:

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;
}



}

还有价格表:

List<MenuPriceByDay> prices = new ArrayList<MenuPriceByDay>();

我想转换成 map :

Map<LocalDate, Statistics> last30DPerDay =  

prices
.stream()
.collect(Collectors.toMap(MenuPriceByDay::getUpdateDate, p -> new Statistics( p.getAvgPrice().doubleValue(),
p.getMaxPrice().doubleValue(),
p.getMinPrice().doubleValue())));

但是我遇到了一个编译问题:

Type mismatch: cannot convert from Map<Date,Object> to 
Map<LocalDate,Statistics>

最佳答案

UpdateDateDate 类型,您尝试收集为 LocalDate,所以您只需要转换 DateLocalDate :

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())
));

关于 Convert Date to LocalDate or LocalDateTime and Back 的更多详细信息

或者你可以像这样创建一个方法:

public LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}

你的代码可以是:

  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())
));

更好的解决方案

最好的解决方案是将 updateDate 类型更改为 LocalDate :

private LocalDate updateDate;

你可以直接使用你的代码

关于Java8 收集 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55129678/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com