Introduction to Lambda Expressions

| Page Views: 192

Simply speaking, Lambda Expressions are basically anonnymous functions.

Lambda Expressions, in the past decade, have been introduced almost all major progamming languages due to their simplicity and conciseness. In java lambda expressions were introduced in Java 8. However you can use the RetroLamda Library if you are still using the previous versions of Java.

Lambda Expressions involve using the lamda operator: ->, basically an arrow pointing to the right.

Then you place the inputs on the left and the function body on the right.

Lambda Expressions mostly get used in Java to replace anonnymous inner classes with just one method. These classes normally implement an interface.

class Button {
        setOnClickListener(OnButtonClickListener listener) {
interface OnButtonClickListener {
    void onButtonClicked();
  1. Then we can listen to the onClick event of the button using an annonymous function:

    Button goButton = ...
    new OnButtonClickListener() {
        void onButtonClicked() {
            // show hello world
  2. Or we can use the Lamda Expression to do the same thing in two lines of code:
    Button goButton = ...
    goButton.setOnClickListener( () -> //show hello world  )

Remember the lambda operator in the above is the arrow symbol(->).

To it's right we can place the code we want to be executed when the event is raised.

To the left you can place inputs. However, the example above has no inputs. So you specify two parantheses: ().

If it was accepting say a paramenter then it would have been this way:

button.setOnClickListener( myArgumnet ->

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post