包含通用Map.Entry参数的方法

Als*_*esh 1 java generics generic-collections java-8

我有两个类非常相似的类

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()));
}
Run Code Online (Sandbox Code Playgroud)

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()));
}
Run Code Online (Sandbox Code Playgroud)

方法参数泛型类型的唯一区别:

Set<Map.Entry<String, List<String>>> headers
Set<Map.Entry<String, Collection<String>>> headers
Run Code Online (Sandbox Code Playgroud)

我不会编码重复.并寻找方式haw我可以在一个重构这两个方法.

我正在尝试使用不同的通用通配符组合编写代码(?super或?extends).但失败了.例如:

Set<Map.Entry<String, ? extends Collection<String>>>
Run Code Online (Sandbox Code Playgroud)

你能不能支持我如何重构这个泛型的想法.谢谢

Ste*_* R. 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()));
}
Run Code Online (Sandbox Code Playgroud)