简体   繁体   中英

Method that contains parameter with generic Map.Entry

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

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM