简体   繁体   中英

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(....)

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

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

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