问题
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