I found some strange behaviour when using lambda with JPA, seems java 8 lambda don't iterate when get a list from another object.
For Example:
List<MyObject> list = anotherObject.getMyObjectList(); // Get The List
list.foreach(myobject -> System.out.println("NOT PRINTED"));
System.out.println("Size?: " + list.size()); // Print The Size = 2
I try with list.stream().foreach() with the same results..
After hours of testing i found a trick
List<MyObject> copyList = new ArrayList<>(list); // copy The List
copyList.foreach(myobject -> System.out.println("OMG IS PRINTED!"));
Huh? Any ideas?, is this a bug? or im doing something wrong? My Entity Clases are working good, all the relations are good... :)
Thanks in Advance :).
It would be good to know the concrete class of the List returned by anotherObject.getMyObjectList()
. It may have a bug in its iterator.
When you copy it to an ArrayList using new ArrayList<>(list)
, the code for this constructor copies the elements from the source list using toArray
and then copies that into a new array that's contained within the ArrayList.
When you call list.forEach
, unless it's been overridden by the concrete class, this ends up calling the default method forEach
of Iterable
, whose implementation is:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
This is just a standard enhanced-for loop here, nothing magic. But this for loop is implemented in terms of the list's iterator. Try writing out a for-loop instead of calling list.forEach(lambda)
, or try calling list.iterator()
and see how many elements you get out of it. If toArray
works but the iteration techniques don't, it seems like a bug in the implementation of the JPA list class's iterator.
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