[英]Method that contains parameter with generic Map.Entry
I have 2 classes with very similar methods 我有两种方法非常相似的课程
Class A: 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()));
}
Class B 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()));
}
The only difference in method argument generic type: 方法参数泛型类型的唯一区别是:
Set<Map.Entry<String, List<String>>> headers
Set<Map.Entry<String, Collection<String>>> headers
I do not wont code duplication. 我不会重复代码。 And looking for way haw I can refactor this two method in one. 寻找方法,可以将这两种方法合而为一。
I was trying write code like with different combination of Generic wildcards (? super or ? extends). 我正在尝试使用通用通配符的不同组合(超级或扩展)编写代码。 But failed with it. 但是失败了。 For examle: 例如:
Set<Map.Entry<String, ? extends Collection<String>>>
Could you pleas support with idea how I can refactor this generic. 您能否请我支持如何重构此泛型的想法? Thanks 谢谢
You have to define a generic type T 您必须定义通用类型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.