本文介绍了Java 8 Collection stream Collectors.toMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码不能为我编译?

Why this code is not compile for me?

我尝试使用stream和toMap选项将List转换为Map

I try to convert List to Map using stream and toMap option

List<CountryToPaymentMethodsDisplayRules>
   paymentMethodDisplayRulesByCountryList =
       gatway.getCountryPaymentMethodsDisplayRulesByCountry();

Map<PaymentMethod, CountryToPaymentMethodsDisplayRules>
   countryToPaymentMethodsDisplayRulesMap = paymentMethodDisplayRulesByCountryList
       .stream()
       .collect(Collectors.toMap(type -> type.getCountryToPaymentMethodsDisplayRules().getPaymentMethod(),
                                 type -> type));

public interface PaymentMethod extends Serializable {
}

public enum PaymentMethodType implements PaymentMethod, Serializable {
}

public interface CountryToPaymentMethodsDisplayRules {
    public PaymentMethod getPaymentMethod();
}

public class CountryToPaymentMethodsDisplayRulesEntity implements CountryToPaymentMethodsDisplayRules, PersistentEntity<Long>, Serializable {
    @Type(type = "com.plimus.core.payment.PaymentMethodTypeUserType")
    @Column(name = "PAYMENT_TYPE")
    private PaymentMethod paymentMethod;
}

这里有什么问题?

推荐答案

您只需要提供带有方法引用和标识的 Collections.toMap()方法。试试这个:

You just need to provide the Collections.toMap() method with a method reference and an identity. Try this:

 Map<PaymentMethod, CountryToPaymentMethodsDisplayRules>
    countryToPaymentMethodsDisplayRulesMap = paymentMethodDisplayRulesByCountryList
    .stream()
    .collect(Collectors.toMap(CountryToPaymentMethodsDisplayRules::getPaymentMethod,x->x);

这篇关于Java 8 Collection stream Collectors.toMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 15:03