lambda 表达式中的错误返回类型:

Posted

技术标签:

【中文标题】lambda 表达式中的错误返回类型:【英文标题】:Bad return type in lambda expression: 【发布时间】: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());

获取异常

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

【问题讨论】:

【参考方案1】:

Stream::reduce(BinaryOperator) 需要 BiFunction&lt;T, T, T&gt; 而在 OP 的代码中,此合约已损坏:(CategoryWise c, CategoryWiseEarnings c2) -&gt; new CategoryWiseEarnings()

此外,数据模型似乎不正确:CategoryWiseEarnings 字段中的 total 应为 Double 以避免冗余转换,类 CategoryWise 缺少 bonus 字段。

因此,解决方案可以是使用Collectors.groupingByCollectors.summingDouble 一起计算地图中的总值,然后将地图条目重新映射到CategoryWiseEarnings

List<CategoryWiseEarnings> result = tripEarnings.getOrders()
    .stream() // Stream<Trips>
    .flatMap(trips -> trips.getCategoryRulesEarnedList().stream()) // Stream<CategoryWise>
    .collect(Collectors.groupingBy(
        cw -> Arrays.asList(cw.getCategoryId(), cw.getCategoryName()) // key -> List<Object>
        LinkedHashMap::new, // keep insertion order
        Collectors.summingDouble(cw -> Double.parseDouble(cw.getBonus()))
    )) // Map<List<Id, Name>, Double>
    .entrySet()
    .stream()
    .map(e -> new CategoryWiseEarnings(
        new CategoryWise(e.getKey().get(0), e.getKey().get(1)), 
        String.valueOf(e.getValue()) // assuming the total is String
    ))
    .collect(Collectors.toList());

【讨论】:

以上是关于lambda 表达式中的错误返回类型:的主要内容,如果未能解决你的问题,请参考以下文章

错误:无法将 lambda 表达式转换为类型“bool”,因为它不是 Kendo Chart 中的委托类型

131.lambda表达式小结

仅对lambda表达式的隐式类型推断?为什么?困惑!

返回 lambda 表达式的函数

C++Lambda表达式作为参数

C++Lambda表达式作为参数