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

时间:2017-08-28 10:20:22

标签: java generics java-8 generic-collections

我有两个类非常相似的类

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

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

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

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

你能不能支持我如何重构这个泛型。 感谢

1 个答案:

答案 0 :(得分: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()));
}
相关问题