Java 8 Lambdas

Java 8 was released a month ago and included:

  • forEach() method in Iterable interface
  • default and static methods in Interfaces
  • Functional Interfaces & Lambda Expressions
  • Java Stream API
  • Java Time API
  • Collection API improvements
  • Concurrency API improvements

The Stream and Time APIs are going to be extremely practical and other improvements are welcomed. However, the one addition I wanted to play around with the most was the lambda expressions.

What is a Lambda Expression?

These types of expressions go by many names. A noticeable one is the usage of anonymous expressions in JavaScript, a language that allows for anonymous functions to be passed.

Seeing is believing though. Let's press!

Java Example

I will show you a contrived object used to perform some math function that accepts two ints and returns an int.

You first need to create an interface that has at most one abstract function. This interface is now known as a functional interface.

interface IMath { 
  int execute(int a, int b);  

You can then use following syntax to create a function by shorthand. The declaration is very different.

class Main {
  public static void main(String\[] args) {
    IMath addObj = (int x, int y)-> x + y; // Instantiate object
    int result = addObj.execute(1,2); // the lambda function is executed
    System.out.println(result);  // 3

What would this contrived example look in another language? Let's go to the language of the web.

JavaScript Example

Although contrived, the following is idiomatic and could exist in production code.

  var execute = function(fn, a, b) {
    return fn(a, b);
  var add = function(a, b){
    return a + b;

  var result = execute(add, 1, 2);

  console.log(result);  // 3


I don't think that the Java community will immediately jump on the chance to use lambdas in the near future. They seem to be an awkward abstraction.

You may also like

  • Angular vs. Vue.js Reactivity

    VueJS is a relatively new library in this ecosystem of JavaScript frameworks that we have. AngularJS has, on the other hand, been long established and has a lot of backing. However, one developer's MV* library may prove to be an interesting alternative.

    Read More >