Reputation: 4387
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;
}
Upvotes: 6
Views: 544
Reputation: 100329
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.
Upvotes: 7