Why does this stream return no element?

删除回忆录丶 提交于 2019-12-17 13:02:35

问题


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

}

this code works fine.

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();

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

EDIT

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

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

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

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/31939827/why-does-this-stream-return-no-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!