I understand that a “yield return” (C# construct) is not available in Java. However, when I do lazy loading in Java/Hibernate. What is the recommended way to iterate over the collection using lazy loading and something similar to yield return ?
I understand that a yield return (C# construct) is not available in Java. However,
Share
There isn’t a yield return statement in Java. The best way (which isn’t to say a super easy way) to do what you want is to write your own implementation of Iterator.
As you can see, this is an all-or-nothing lazy loader. You might also consider an incremental lazy loader that loads data only as you progress through the collection. One case where this is useful is when the collection contains a very large number of records.
You may also want/need be more specific, and write a lazy loading wrapper of Collection, or List. The technique would be similar, but would generally be more work (a lazy loaded List might need a lazy loded Iterator, and you might have to be concerned with thread safety, just to think of a few things).
This is basically doing by hand what c#’s yield and yield return keywords do under the hood with a compile time transformation.