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;
}
Using Stream findFirst() Method: The findFirst() method will returns the first element of the stream or an empty if the stream is empty. Approach: Get the stream of elements in which the first element is to be returned. To get the first element, you can directly use the findFirst() method.
Generating Streams With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
If a value is present in this Optional , returns the value, otherwise throws NoSuchElementException . An Optional will never expose its value if it is null . If you really have to, just check isPresent() and return null yourself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With