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

查看:13
本文介绍了是否可以在 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天全站免登陆