简体   繁体   English

具有通用类型的Java collect()流

[英]Java collect() Stream with generic type

Is there way to collect() generic items from a stream ? 有没有办法从stream collect()通用项目?

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: 因此,如果代码的目的确实是基于类型参数过滤Response对象,则对解决方案的猜测很可能是:

@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> responses作为参数,尽管我确实应该使用通配符边界List<Response<? extends Data>> responses 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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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