Java 8 code KATAs IV – Method References Example

In this series of posts, I will be posting simple java 8 code katas.

Part I – Interface with default methods
Part II – Interface with static methods
Part III – Functional Interfaces & Lambda Expressions
Part IV – Method References
Part V – java.util.function package
Part VI – Streams

This post would be about method references.

See the example below:

MethodReferencesExample.java


package com.idodevjobs;

import java.util.Arrays;
import java.util.List;

public class MethodReferencesExample {
    public static void main(String[] args) {
        List<Employee> empList = Arrays.asList(new Employee(101, "mark", 23), new Employee(102, "ron", 20), new Employee(103, "jon", 28));
        empList.sort(Employee::compareByAge);
        System.out.println(empList);
    }
}

class Employee {
    private int id;
    private String name;
    private int age;

    public Employee() {
    }

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public static int compareByAge(Employee emp1, Employee emp2) {
        return emp1.getAge() - emp2.getAge();
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Method references can be used as an alternative to Lambda Expressions when we need to call an existing method with a name instead of defining new one.

In our example, to sort the array list – instead of using a lambda expression or pass a comparator implementation, we are passing the existing method as a method reference using Employee::compareByAge operator.

Advertisements
This entry was posted in java and tagged . Bookmark the permalink.

5 Responses to Java 8 code KATAs IV – Method References Example

  1. Pingback: Java 8 code KATAs I – Interface with default methods Example | iDoDevJobs

  2. Pingback: Java 8 code KATAs III – FunctionalInterface & Lambda Expressions Example | iDoDevJobs

  3. Pingback: Java 8 code KATAs II – Interface with static methods Example | iDoDevJobs

  4. Pingback: Java 8 code KATAs V – java.util.function Example | iDoDevJobs

  5. Pingback: Java 8 code KATAs VI – Streams | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s