如何使用Java流将没有泛型的列表转换为有泛型的列表?

4

我想将一个没有泛型的 List 转换为 List<MyConcreteType>

我还需要筛选出只有我的具体类型。

我的当前流逻辑是这样的:

List list = new ArrayList();
Object collect1 = list.stream().filter((o -> o instanceof MyConcreteType)).collect(Collectors.toList());

但结果是我得到了一个 Object 而不是一个 List。有没有一种方法可以将这个 Stream 转换成一个 List<MyConcreteType>


只需将其转换为 List<MyConcreteType> typedList = (List<MyConcreteType>) list - Boris the Spider
@BoristheSpider 但我需要先过滤它——因为它可能包含其他项目。 - pixel
4
"""list.stream().filter(MyConcreteType.class::isInstance).map(MyConcreteType.class::cast).collect(Collectors.toList()) 然后""" - Boris the Spider
1个回答

9

使用参数化类型而不是原始类型,并使用map将通过过滤器的对象转换为MyConcreteType

List<?> list = new ArrayList();
List<MyConcreteType> collect1 = 
    list.stream()
        .filter((o -> o instanceof MyConcreteType))
        .map(s-> (MyConcreteType) s)
        .collect(Collectors.toList());

或者(与Boris在评论中建议的类似):
 List<?> list = new ArrayList();
 List<MyConcreteType> collect1 = 
     list.stream()
         .filter(MyConcreteType.class::isInstance)
         .map(MyConcreteType.class::cast)
         .collect(Collectors.toList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接