How Lambdas can be useful in Java

I’m revising for the OCP (Oracle Certified Professional Java Programmer ), and running over Lambdas at the moment. In tutorials I see many of them seem to focus on what they are , what they do , streams etc.

Not much on how they can be used to improve code ( and making less Class files in particular ).

Here we have an Animal class that has a couple of subclasses. The Animal subclasses will print out their behaviour polymorphically (and its all abit of a mess). I won’t get into Inheritance, classes and composition. But I will say less classes = better ( sometimes hard to avoid in Java ).

The Animal subclasses will print out their behaviour polymorphically.

Complex way 

So here you have 4 class files (Animal, Fish, Kangaroo, Man), you could easily put printMyBehaviour in an inferface also that would make 5

Simple Way Lambdas 

Here is how Lamdbas can improve this ( note I’ve used the oven ready Consumer Lambda included java.util.function ). In preference to making my own Functional interface (less classes if possible remember).

Lambdas are great for a couple of lines of code (but if its more than 2 or 3 lines of code, I’d stick to making them in their own method the old way, rather than using lambdas, them inline like this).

They can get counter productive the (hard to read, there’s a tendency to cram stuff in and make it less readable, something I’ve seen way to often in Javascript this is especially true for arrow functions, anonymous functions…

Handy Lambda classes / Function interfaces

There are a number of existing Lambdas for common things ( not just in the streams API ), for example the ones below (use an existing one if it makes sense, less new Class/Interface files ! ):

  • Predicate
  • Consumer
  • Supplier
  • Comparator

Leave a Comment