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 中转换流?
				
        
 
            
        基础教程推荐
- 从 python 访问 JVM 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				