Nati
Nati

Reputation: 1032

Java collect() Stream with generic type

Is there way to collect() generic items from a stream ?

This is what I want to do...

private <T extends Data> List<Response<T>> validateAndGetResponses(List<Response> responses, Class<T> clazz) {
        Supplier<List<Response<T>>> supplier = LinkedList::new;

        List<Response<T>> list = responses.stream().filter(
                response -> clazz.isInstance(getData(response))).collect(Collectors.toCollection(supplier));
        return list;

}

This doesn't work, I get

no suitable method found for collect(....)

Upvotes: 2

Views: 11719

Answers (2)

Nati
Nati

Reputation: 1032

So the problem was I used a raw type List<Response> responses as an argument, though I really should of used a wildcard boundary, List<Response<? extends Data>> responses.

This is the complete method:

@SuppressWarnings("unchecked")
private  <T extends Data> List<T> validateAndGetResponses(List<Response<? extends Data>> responses, Class<T> clazz) {
    return responses.stream().map(this::getData)
                             .filter(clazz::isInstance)
                             .map(r -> (T) r)
                             .collect(Collectors.toList());
}

Upvotes: 5

fabriziocucci
fabriziocucci

Reputation: 782

So, if the purpose of the code is indeed filtering the Response objects based on the type parameter, a wild guess of the solution could be:

@SuppressWarnings("unchecked")
private <T extends Data> List<Response<T>> validateAndGetResponses(List<Response<? extends Data>> responses, Class<T> clazz) {
    return responses.stream()
            .filter(response -> clazz.isInstance(getData(response)))
            .map(response -> (Response<T>) response)
            .collect(Collectors.toCollection(LinkedList::new));
}

Upvotes: 5

Related Questions