2017-03-17 56 views
0

爲什麼這段代碼不適合我?Java 8 Collection流Collectors.toMap

我嘗試轉換列表使用流和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; 
} 

這裏有什麼問題到地圖?

+2

,那麼您已經提供了一些代碼(我已經重新格式化你 - 請閱讀的格式幫助,避免發佈,直到預覽顯示合理的格式),但你有沒有用什麼方式說,不起作用...理想情況下,將其重寫爲[mcve]。 –

+2

我找不到方法getCountryToPaymentMethodsDisplayRules。你能提供一些有關這種方法的信息嗎? –

+3

確實,這裏*錯在哪裏?它是否會產生異常?它是否會生成空白的地圖?它會無限期地運行嗎?我們可能永遠不知道! –

回答

1

發現問題感謝

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

你真的認爲調用一個不存在的方法的發現可以通過刪除方法調用來解決,對未來的讀者有什麼價值? – Holger

7

你只需要提供Collections.toMap()方法與方法的引用和身份。試試這個:

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

不明白爲什麼這是upvoted。方法參考並不解決任何問題,並且不存在具有單個參數的「Collectors.toMap」函數... – Roland

+0

@Roland,你說得對。這是我的錯誤,我會立即修復它:) – CraigR8806

+1

好得多;-) – Roland