为什么这个流没有返回元素? [英] Why does this stream return no element?

查看:64
本文介绍了为什么这个流没有返回元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将以下代码编写为流:

I tried to write the following code as a stream:

AbstractDevice myDevice = null;

for (AbstractDevice device : session.getWorkplace().getDevices()) {

    if (device.getPluginconfig().getPluginType().getId() == 1) {
        myDevice =  device;
    }

}

此代码正常。

但当我像这样重写它时它不再起作用了:

But when I rewrite it like this it doesn't work anymore:

myDevice = session.getWorkplace().getDevices().stream()
                  .filter(s -> s.getPluginconfig().getPluginType().getId() == 1)
                  .findFirst().get();

可选我从stream没有值。为什么?

The Optional which I get back from the stream has no values in it. Why?

编辑

当我尝试这个时(我还有两台设备)返回 getDevices()):

When I try this (I still get two devices back from getDevices()):

 List<AbstractDevice> testList = session.getWorkplace().getDevices()
                                        .stream().collect(Collectors.toList());

testList 为空。所以我的 List 设备的流似乎出了问题?

the testList is empty. So it seems like something goes wrong with the stream of my List of devices?

这是一个JavaEE应用程序而我从相应的实体获取我的设备:

It's a JavaEE application and I get my Devices from the corresponding entity:

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(name = "Workplace_AbstractDevice",
            joinColumns = {
                @JoinColumn(name = "Workplace", referencedColumnName = "ID")
            },
            inverseJoinColumns = {
                @JoinColumn(name = "AbstractDevice", referencedColumnName = "ID")
            })
@OrderColumn
private List<AbstractDevice> devices = new ArrayList<AbstractDevice>();


public List<AbstractDevice> getDevices() {
    return devices;
}


推荐答案

似乎您正在使用EclipseLink在2.6版本之前,点击 Bug#433075 。此设备字段将替换为 IndirectList (通过反射)扩展 Vector 类并执行延迟初始化。它是为没有 stream()方法的旧Java版本编写的,因此实际调用 stream()在未初始化的列表上返回一个空流。

Seems that you are using EclipseLink prior to 2.6 version and hit the Bug#433075. This devices field is replaced with IndirectList (via reflection) which extends the Vector class and performs a lazy initialization. It was written for an older Java version which had no stream() method, so the stream() is actually called on uninitialized list returning an empty stream.

该错误是已修复,因此您可能需要将EclipseLink更新为2.6版本。在EclipseLink 2.6中,另一个类是在JDK 1.8上运行时使用,这是对流友好的。

The bug is fixed, thus you probably have to update the EclipseLink to 2.6 version. In EclipseLink 2.6 another class is used when running on JDK 1.8 which is stream-friendly.

这篇关于为什么这个流没有返回元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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