2017-08-28 21 views
1

我有2類非常相似的方法方法包含與通用Map.Entry的參數

A類:

String getString(Set<Map.Entry<String, List<String>>> headers) { 
    return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream(). 
      collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator())); 
} 

B類

String getString(Set<Map.Entry<String, Collection<String>>> headers) { 
    return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream(). 
      collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator())); 
} 

在方法參數通用唯一的區別類型:

Set<Map.Entry<String, List<String>>> headers 
Set<Map.Entry<String, Collection<String>>> headers 

我不會編碼重複。尋找方法我可以在一個重構這兩個方法。

我正在嘗試編寫類似於通用通配符(?super或?extends)的不同組合的代碼。但失敗了。例如:

Set<Map.Entry<String, ? extends Collection<String>>> 

你能否請求支持與想法如何我可以重構這個通用。 感謝

+4

我把你的第一種方法,並修改了方法簽名:'字符串的getString(集 >>頭文件){...}並且編譯得很好。所以:無法複製! – GhostCat

+2

從這個意義上說:尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現它所需的最短代碼。沒有明確問題陳述的問題對其他讀者無益。請參閱:如何創建[mcve]。使用「編輯」鏈接來改善你的*問題* - 不要通過評論添加更多信息。謝謝!你看,*但失敗*不是我們可以幫助的問題描述。問題是什麼?錯誤信息? – GhostCat

回答

8

你必須定義一個通用的T型

public <T extends Collection<String>> String getString(Set<Map.Entry<String, T>> headers) { 
    return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream().collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator())); 
} 
+0

你不需要。使用'Set >>,就像OP描述的那樣,工作順利。 – Holger