Sitemap

Java8: Lambdas & Method References

2 min readMar 7, 2021

--

Method reference is a shorthand notation of a lambda expression to call a method. str -> System.out.println(str) can be replaced with System.out::println

Press enter or click to view image in full size
Photo by Brian Kyed on Unsplash

Let’s think we going to call following method using a lambda implementation. As you might know Consumer is function interface provided by java where we can send a our implementation as a parameter.

private static void show(List<Integer> ls, Consumer consumer){
for(Integer I: ls){
consumer.accept(I);
}
}

We can execute it like this using a lambda implementation, here we sending print method to consumer so that consumer will print when we execute accept method.

List<Integer> ls = Arrays.asList(6,7,8);
show(ls, o -> System.out.println(o));

Now let’s try do the same using a method reference feature,

List<Integer> ls = Arrays.asList(2,3,5);
show(ls, System.out::println);

In this code we have used method reference instead of lambda expression.

Another Example

List names = new ArrayList();
names.add("Nuwan");
names.add("Sen");
names.forEach(System.out::println);

Another Example 2

Comparator<String> sc = (first, second) -> first.compareToIgnoreCase(second);

can be replaced with

Comparator<String> stringIgnoreCase = String::compareToIgnoreCase;

Like this

Comparator<String> sc2=String::compareToIgnoreCase;
List<String> values = Arrays.asList("Sen", "Nuwan","Kandy");
Collections.sort(values, sc2);
System.out.println(values);

Another Example 3

Function<String, Job> jobCreator2 = (jobName) -> return new Job(jobName);

can be replaced with

Function<String, Job> jobCreator = Job::new;

Example 4 Constructor Reference

Let’s say we want to create a object of this class

class Job{
String s;
Job(String s){
this.s=s;
}
}

We can do it like this

Function<String, Job> jobCreator = Job::new;
Job job= jobCreator.apply("dsds");
System.out.println( job.s);

First line of code not neccerally create the object, it actually happens at apply().

Get Nuwan Zen’s stories in your inbox

Join Medium for free to get updates from this writer.

These examples works with methods passed with single arguments. For example if you are looping a list of objects and wants to print a single field then you may have to override toString method of the object.

Read my other blogs:

--

--

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!