[英]Method that contains parameter with generic 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
我不會重復代碼。 尋找方法,可以將這兩種方法合而為一。
我正在嘗試使用通用通配符的不同組合(超級或擴展)編寫代碼。 但是失敗了。 例如:
Set<Map.Entry<String, ? extends Collection<String>>>
您能否請我支持如何重構此泛型的想法? 謝謝
您必須定義通用類型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()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.