【发布时间】:2021-11-01 22:31:58
【问题描述】:
List<CategoryWiseEarnings> data = tripEarnings.getOrders()
.stream()
.flatMap(getCategoryRulesEarnedList -> getCategoryRulesEarnedList.getCategoryRulesEarnedList().stream())
.collect(Collectors.groupingBy(foo -> foo.getCategoryId()))
.entrySet()
.stream()
.map(e -> e.getValue()
.stream()
.reduce((c,c2) -> new CategoryWiseEarnings(
new CategoryWise(
c.getCategoryName(),
c.getCategoryId()
),
c.getBonus()
))
)
.map(f -> f.get())
.collect(Collectors.toList());
获取异常
: lambda 表达式中的错误返回类型:
CategoryWiseEarnings无法转换为CategoryWise
public class CategoryWiseEarnings {
@JsonProperty("category")
private CategoryWise earnings;
@JsonProperty("total_amount")
private String totalAmount;
}
public class CategoryWise {
@JsonProperty("category_id")
Long categoryId;
@JsonProperty("category_name")
String categoryName;
public CategoryWise(String categoryName, Long categoryId) {
this.categoryName = categoryName;
this.categoryId = categoryId;
}
}
这是我想使用流和 lambda 函数编写的代码,如果我这样编写它可以正常工作:
for (Trips tripsOrders : tripEarnings.getOrders()) {
if (!tripsOrders.getCategoryRulesEarnedList().isEmpty()) {
for (CategoryWise c : tripsOrders.getCategoryRulesEarnedList()) {
if (hashMapCategory.containsKey(c.getCategoryId())) {
// hashmapk.put(c.getCategoryId(),new CategoryWiseEarnings(new CategoryWise(c.getCategoryName(),c.getCategoryId()),c.getBonus()+hashmapk.get(c.getCategoryId()).getTotalAmount()));
CategoryWiseEarnings categoryObject = hashMapCategory.get(c.getCategoryId());
categoryObject.setTotalAmount(Double.toString(
Double.parseDouble(c.getBonus())
+ Double.parseDouble(categoryObject.getTotalAmount())
));
hashMapCategory.put(c.getCategoryId(), categoryObject);
} else {
hashMapCategory.put(c.getCategoryId(), new CategoryWiseEarnings(new CategoryWise(c.getCategoryName(), c.getCategoryId()), c.getBonus()));
}
}
}
}
List<CategoryWiseEarnings> list = new ArrayList<CategoryWiseEarnings>(hashMapCategory.values());
【问题讨论】:
标签: java lambda java-8 java-stream