为什么这个流 return 没有元素?

Why does this stream return no element?

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

AbstractDevice myDevice = null;

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

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

}

这段代码工作正常。

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

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

我从流中返回的 Optional 没有任何值。为什么?

编辑

当我尝试这个时(我仍然从 getDevices() 得到两个设备):

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

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

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

@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;
}

似乎您使用的是 2.6 版本之前的 EclipseLink 并点击了扩展 Vector class 并执行延迟初始化的 Bug#433075. This devices field is replaced with IndirectList(通过反射)。它是为没有 stream() 方法的旧 Java 版本编写的,因此 stream() 实际上是在返回空流的未初始化列表上调用的。

错误是 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 流友好。