【问题标题】:Java 8 Collection stream Collectors.toMapJava 8 集合流 Collectors.toMap
【发布时间】:2017-08-08 21:50:24
【问题描述】:

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

我尝试使用流和 toMap 选项将列表转换为地图

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

这里有什么问题?

【问题讨论】:

  • 好吧,你已经提供了一些代码(我已经为你重新格式化了 - 请阅读格式化帮助并避免发布,直到预览显示合理的格式),但你还没有说它不以什么方式'不起作用...理想情况下,将其重写为minimal reproducible example
  • 我找不到方法 getCountryToPaymentMethodsDisplayRules。你能提供一些关于这个方法的信息吗?
  • 确实,这里的有什么问题?它会产生异常吗?它会产生一张空地图吗?它会无限期地运行吗?我们可能永远不会知道!

标签: java java-8 java-stream collectors


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    找到问题谢谢

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

    【讨论】:

    • 你真的认为发现调用不存在的方法可以通过删除方法调用来修复,对未来的读者有什么价值吗?
    猜你喜欢
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2015-10-20
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多