Method that contains parameter with generic Map.Entry

263 views Asked by At

I have 2 classes with very similar methods

Class 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

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

1

There are 1 answers

1
Stefano R. On

You have to define a generic type 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()));
}