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 中转换流?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
