是否可以在Java 8中强制转换流? [英] Is it possible to cast a Stream in Java 8?

查看:118
本文介绍了是否可以在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中强制转换流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆