Why does this thread not return an element?

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 great.

But when I rewrite it like this, it no longer works:

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

Optional , which I return from the stream, has no values ​​in it. Why?

EDIT

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

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

testList empty. So it seems that something went wrong with the flow of my List devices?

This is a JavaEE application, and I get my Devices from the corresponding object:

 @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; } 
+5
source share
1 answer

It seems that you are using EclipseLink before version 2.6 and get into Error # 433075 . This devices field is replaced with an IndirectList (via reflection), which extends the Vector class and performs lazy initialization. It was written for an old version of Java that did not have a stream() method, so stream() actually called in an uninitialized list that returns an empty stream.

A bug has been fixed, so you may have to upgrade the version of EclipseLink to version 2.6. In EclipseLink 2.6, another class is used when working on JDK 1.8 , which is stream-friendly.

+6
source

All Articles