Java 8 Collection stream Collectors.toMap

时间:2017-03-17 11:03:08

标签: java java-8 java-stream collectors

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

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

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

这里有什么问题?

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:0)

发现问题谢谢

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