[英]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.