Java 8 集合流 Collectors.toMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42855807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:54:35 来源:igfitidea点击:
Java 8 Collection stream Collectors.toMap
提问by Yaron Tzur
Why this code is not compile for me?
为什么这段代码不适合我编译?
I try to convert List to Map using stream and toMap option
我尝试使用流和 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;
}
What is wrong here?
这里有什么问题?
回答by CraigR8806
You just need to provide the Collections.toMap()
method with a method reference and an identity. Try this:
您只需要为该Collections.toMap()
方法提供一个方法引用和一个标识。试试这个:
Map<PaymentMethod, CountryToPaymentMethodsDisplayRules>
countryToPaymentMethodsDisplayRulesMap = paymentMethodDisplayRulesByCountryList
.stream()
.collect(Collectors.toMap(CountryToPaymentMethodsDisplayRules::getPaymentMethod,x->x);
回答by Yaron Tzur
Found the problem thanks
发现问题谢谢
Map<PaymentMethod, CountryToPaymentMethodsDisplayRules>
countryToPaymentMethodsDisplayRulesMap = paymentMethodDisplayRulesByCountryList
.stream()
.collect(Collectors.toMap(type -> type.getPaymentMethod(),
type -> type));