Is it possible to cast a Stream in Java 8?(是否可以在 Java 8 中转换流?)
问题描述
是否可以在 Java 8 中转换流?假设我有一个对象列表,我可以这样做来过滤掉所有其他对象:
Is it possible to cast a stream in Java 8? Say I have a list of objects, I can do something like this to filter out all the additional objects:
Stream.of(objects).filter(c -> c instanceof Client)
不过,在此之后,如果我想对客户做点什么,我需要对他们每个人进行强制转换:
After this though, if I want to do something with the clients I would need to cast each of them:
Stream.of(objects).filter(c -> c instanceof Client)
.map(c -> ((Client) c).getID()).forEach(System.out::println);
这看起来有点难看.是否可以将整个流转换为不同的类型?就像将 Stream<Object>
转换为 Stream<Client>
?
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object>
to a Stream<Client>
?
请忽略这样一个事实,即这样做可能意味着糟糕的设计.我们在我的计算机科学课上做过类似的事情,所以我正在研究 java 8 的新特性,并且很好奇这是否可能.
Please ignore the fact that doing things like this would probably mean bad design. We do stuff like this in my computer science class, so I was looking into the new features of java 8 and was curious if this was possible.
推荐答案
我认为没有开箱即用的方法.一个可能更清洁的解决方案是:
I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:
Stream.of(objects)
.filter(c -> c instanceof Client)
.map(c -> (Client) c)
.map(Client::getID)
.forEach(System.out::println);
或者,如评论中所建议的,您可以使用 cast
方法 - 不过前者可能更容易阅读:
or, as suggested in the comments, you could use the cast
method - the former may be easier to read though:
Stream.of(objects)
.filter(Client.class::isInstance)
.map(Client.class::cast)
.map(Client::getID)
.forEach(System.out::println);
这篇关于是否可以在 Java 8 中转换流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 Java 8 中转换流?
基础教程推荐
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01