-3

Want to convert following for loop from Java 7 to Java 8 (lambda).

for (Employee e : list) {
    session.evict(e);
}

Here, session is Hibernate Session. My intention here is to change the above mentioned working java 7 code to Java 8 with feature of lambda or method reference.

Hanamant Jadhav
  • 627
  • 7
  • 12
  • 4
    This code is perfect for Java 8 too! – ernest_k Jul 08 '21 at 06:47
  • 6
    That will work with no change in Java 8. If you mean you want to use streams, I'm not sure how that would help, but `list.forEach(e -> session.evict(e))` should do the trick. – Federico klez Culloca Jul 08 '21 at 06:47
  • 1
    This code is perfect for Java 8. I just want to use lambda expression here. @ernest_k – Hanamant Jadhav Jul 08 '21 at 06:52
  • @FedericoklezCulloca - Thanks for the input. I tried this before posting the question. It was giving me compilation error as "Local variable session defined in an enclosing scope must be final or effectively final". Is that okay to make session as final. – Hanamant Jadhav Jul 08 '21 at 06:54
  • @Lino - I was trying to use lambda expression here. – Hanamant Jadhav Jul 08 '21 at 06:54
  • 3
    "I just want to use lambda expression here." - In that case you should state so in your question. The next time please keep in mind that the more precise you are in asking the more precise will answers be (or attract answers instead of questions in the first place). You also might want to (re)read [ask]. – Thomas Jul 08 '21 at 06:55
  • 1
    Potentially worth a read: [Java 8 Iterable.forEach() vs foreach loop](https://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop) – Lino Jul 08 '21 at 07:10
  • 1
    @HanamantJadhav re: making `session` final, without knowing where and how `session` was declared I wouldn't know. Try and see if that works with your code. – Federico klez Culloca Jul 08 '21 at 07:11

1 Answers1

2

You can switch the expression to method reference lambda:

list.forEach(session::evict);

Note that if Session.evict throws an Exception then you'll need to either trap / convert to RuntimeException in order for the above to compile, or use a longer form of lambda in the loop.

list.forEach(e -> {
    try {
        session.evict(e);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
});
DuncG
  • 12,137
  • 2
  • 21
  • 33
  • Thanks @DuncG ! This solution worked for me. The code which I have mentioned in Question is working. My intention was to change it with Java 8 features (lambda). – Hanamant Jadhav Jul 08 '21 at 09:34