Lambdas: some rules of thumb
Most of the time, using labmda expressions in Java is fairly straightforward, as we saw in our introduction.
On this and the following pages, we will tackle a few more details that will emerge sooner or later as you make more extensive use of lambdas:
- which variables can be accessed from a labmda expression (and which cannot)?
- what data can be modified from a lambda expression?
- can you throw an exception from a lambda expression? how is it caught and handled?
- what other restrictions are there on the code that lambda expressions can execute?
- do lambdas have any performance benefits or tradeoffs?
Working with lambdas: some rules of thumb
Most of the time, we can work to a few rules of thumb. We will look at some of these in more
detail, including exceptions to the rules:
- variable names refer to the same variables as they would do in the surrounding method;
- method-local variables must be effectively final;
- the lambda's own variables must not clash with the local variables of the
surrounding method;
- lambda expressions cannot update variables outside of the lambda expression itself;
- they can modify data referred to by variables, e.g. if a final variable 'list'
refers to an ArrayList, the lambda expression can still call list.add() and add items
to the list, but...
- it is usually bad practice to do so unless the lambda is a
Consumer
;
- lambda expressions can throw (checked) exceptions declared in the corresponding functional interface; but...
- the general-purpose functional interfaces do not allow checked exceptions to be thrown: in practice,
this rules out throwing checked exceptions when working with streams;
- lambda expressions peform similarly to writing the equivalent code using an interface implementation
(though this may be a shifting target depending on your JVM version);
- Streams are a sloghtly more "heavyweight" means of iteration compared to an equivalent loop or simple
Iterator
.
- using lambdas and streams won't magically turn an inefficient algorithm into an efficient one, and can make it
tantalisingly easy to write inefficient algorithms if you are not on your guard!
These rules of thumb are outlined in more detail over the following pages:
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.