Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda Iteration List from JPA [duplicate]

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 :).

like image 253
DarkZaioN Avatar asked Apr 23 '14 16:04

DarkZaioN


1 Answers

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.

like image 121
Stuart Marks Avatar answered Sep 24 '22 21:09

Stuart Marks