Using method references in Java

Using method references in Java

In the Java programming language, method references are a unique feature introduced in Java 8. They provide Java developers with a shorter, more easily readable syntax for creating custom, user-defined lambda expressions. When a custom lambda expression simply calls an existing method, the :: operator is used in the lambda expression.

Using method references in Java

Syntax of a basic Java lambda method expression.

ClassName::methodName

For example, instead of Java user.

comp_name.forEach(comp_name -> System.out.println(comp_name));

We could also write it like this.

comp_name.forEach(System.out::println);

Both of these perform the same program operation logic task.

Static method reference in Java.

Syntax of a static method.

ClassName::staticMethod

Example of a Java static method class.

import java.util.List;

import java.util.Arrays;

public class Main {

static void preview(String software) {

System.out.println(software);

}

public static void main(String[] args) {

List<String> softwares =

Arrays.asList(“Windows 11”, “Apple Mac”, “Linux”, “Tally”, “MS Word 2021”);

softwares.forEach(Main::preview);

}

}

In this example.

Main::preview

Here is a reference to the static preview() function method.

Equivalent lambda expression.

softwares.forEach(software -> Main.display(software));

Reference to an instance method of an object in Java.

Syntax of an instance method of an object.

object::instanceMethod

Example of an instance method of an object.

import java.util.List;

import java.util.Arrays;

class Msoffice {

void print(String text) {

System.out.println(text);

}

}

public class Main {

public static void main(String[] args) {

Msoffice msoffice = new Msoffice();

List<String> applications =

Arrays.asList(“Excel”, “Word”, “Powerpoint”, “Outlook”, “Visio”, “One Note”);

applications.forEach(msoffice::print);

}

}

Explain of above program.

class Msoffice {

void print(String text) {

System.out.println(text);

}

}

Using Objects in Java.

Msoffice msoffice = new Msoffice();

List<String> applications =

Arrays.asList(“Excel”, “Word”, “Powerpoint”, “Outlook”, “Visio”, “One Note”);

applications.forEach(msoffice::print);

The equivalent lambda expression is.

applications.forEach(application -> printer.print(application));

A reference to a class’s instance method in Java.

Instance method references are used in Java programs when a user-defined class method is called on each object.

The syntax for an instance method reference is.

ClassName::instanceMethod

Example of an instance method reference.

List<String> city =

import java.util.List;

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

List<String> city =

Arrays.asList(“Mumbai”, “Kolkata”, “Bengaluru”, “Chennai”, “Hyderabad”);

city.stream()

.map(String::toUpperCase)

.forEach(System.out::println);

}

}

Its output.

MUMBAI

KOLKATA

BENGALURU

CHENNAI

HYDERABAD

The equivalent lambda expression.

city.stream()

.map(city -> city.toUpperCase())

.forEach(city -> System.out.println(city));

A reference to a constructor in Java.

Method references can also be used to call constructors in Java programs.

Syntax of a reference to a constructor.

ClassName::new

An example of a reference to a constructor.

List<String> country =

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

List<String> country =

Arrays.asList(“India”, “Switzerland”, “Denmark”, “Sweden”, “Germany”, “Netherlands”);

List<String> output =

country.stream()

.map(StringBuilder::new)

.map(StringBuilder::toString)

.collect(Collectors.toList());

output.forEach(System.out::println);

}

}

Here in this example.

StringBuilder::new

This is a constructor reference method.

The equivalent is a lambda expression.

country -> new StringBuilder(country)

Method reference with a comparator in Java.

In Java programs, method references are commonly used with data element sorting methods.

An example of a method reference with a comparator.

List<String> names =

import java.util.Arrays;

import java.util.List;

import java.util.Comparator;

public class Main {

public static void main(String[] args) {

List<String> spokenlanguage =

Arrays.asList(“English”, “Mandarin Chinese”, “Hindi”, “Spanish”, “French”, “Arabic”, “Bengali”);

// Here it sorts all spoken language words alphabetically

spokenlanguage.sort(String::compareTo);

System.out.println(“Ascending Alphabet sequence = ” + spokenlanguage);

// here it Sort by string length by each spoken language word

spokenlanguage.sort(Comparator.comparingInt(String::length));

System.out.println(“Language Sorted by their length = ” + spokenlanguage);

}

}

Main Four Types of Java Method References

#Java Method TypeType of Each Method SyntaxDetail Example
1.Static methodWe use it for Static method – ClassName::staticMethodEx: Math::abs
2.Instance method of objectWe use it for Instance method of object – object::methodEx: System.out::println
3.Instance method of classWe use it for Instance method of class -ClassName::methodEx: String::toUpperCase
4.ConstructorWe use it for Constructor – ClassName::newEx: ArrayList::new

Lambda vs. method reference expressions in Java.

Lambda expression.

numbers.forEach(n -> System.out.println(n));

Java Method Reference.

numbers.forEach(System.out::println);

Lambda expression.

country.stream()

.map(country -> country.toUpperCase())

.forEach(System.out::println);

Java Method Reference.

country.stream()

.map(String::toUpperCase)

.forEach(System.out::println);

Conclusion of Using Method References.

A method reference in a Java program does not create a new method. It simply provides a shorthand way to reference an existing, user-defined, custom method.

Lambda expression.

p -> object.method(p)

Java Method Reference.

object::method

Method references in Java programs are primarily used in Java 8 functional programming and to simplify and make stream code easier to read.

Leave a Reply