Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How is java generics with wildcards different from non java generic list?

Asked by Andrew Jenkins Oct 12, 2022 1.3K views 1 answer
Share

About this question

 There is a problem on Exercism Java track that requires writing a function to flatten an arbitrarily nested list to a flattened list without null values. For Example

input: [1,[2,3,null,4],[null],5]

output: [1,2,3,4,5]

Here is the solution I wrote for it without using wildcards.


public List flatten(List<Object> two) {
    Function<Object, List> mapper = item -> (item instanceof List) ? flatten((List) item) : Collections.singletonList(item);
    return (List) two.stream()
            .filter(x -> x != null)
            .map(mapper)
            .flatMap(x -> x.stream())
            .collect(Collectors.toList());
}
Here is my solution with the wildcard generics. My IDE was happier with this solution.
public List<Object> flatten(List<?> two) {
    Function<Object, List<?>> mapper = item -> (item instanceof List) ? flatten((List<?>) item) : Collections.singletonList(item);
    return two.stream()
            .filter(Objects::nonNull)
            .map(mapper)
            .flatMap(List::stream)
            .collect(Collectors.toList());
}

Is it ok to use the wildcard in this case? Which solution would you prefer? Any other comments about the code are also welcome.

Your answer

1 Answer