如何使用collect获取List<TestClone>而非List<Object>?
问题解决:将Stream结果收集为List
你当前的map操作存在类型不一致的问题——当e.schema == null时返回的是List<TestClone>,否则返回单个TestClone,这就导致Stream中的元素类型变成了Object,自然无法直接收集为List<TestClone>。
解决方法是把map替换成flatMap,它可以将集合类型的元素“展开”为单个元素的流,让整个Stream的元素类型统一为TestClone,之后就能正常收集为ArrayList<TestClone>了。
修改后的代码如下:
public static List<TestClone> getTypes(List<TestClone> args) { return args.stream().flatMap(e -> { if (e.schema == null) { return getAllExportArgs(e).stream(); } else { return Stream.of(e); } }).collect(Collectors.toCollection(ArrayList<TestClone>::new)); } public static List<TestClone> getAllExportArgs(TestClone args) { // 返回List<TestClone>的逻辑保持不变 }
关键说明:
flatMap要求返回Stream类型,所以对返回集合的分支,调用stream()将List<TestClone>转换为Stream<TestClone>;- 对返回单个对象的分支,用
Stream.of(e)把单个TestClone包装成仅含该元素的Stream; - 统一元素类型后,
collect操作就能正确生成ArrayList<TestClone>,完全匹配方法的返回类型。
内容的提问来源于stack exchange,提问作者vasu
相关产品推荐
相关产品推荐

