JPA Java Lambda Iteration List

I found strange behavior when using lambda with JPA, it seems that java 8 lambda does not iterate when retrieving a list from another object.

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 am trying to use 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!"));

AND? Any ideas ?, is this a mistake? or are they doing something wrong? My member entities work well, all relationships are good ... :)

Thanks at Advance :).

+4
source share
2 answers

It would be useful to know the specific List class returned anotherObject.getMyObjectList(). It may have an error in its iterator.

ArrayList new ArrayList<>(list), toArray, , ArrayList.

list.forEach, , forEach Iterable, :

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

, . . for-loop list.forEach(lambda) list.iterator() , . toArray , , JPA.

+3

Source: https://habr.com/ru/post/1537755/


All Articles