Java 8 Collection stream Collectors.toMap

自闭症网瘾萝莉.ら 提交于 2019-12-10 12:25:36

问题


Why this code is not compile for me?

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

What is wrong here?


回答1:


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



回答2:


Found the problem thanks

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


来源:https://stackoverflow.com/questions/42855807/java-8-collection-stream-collectors-tomap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!