In this post, we will learn on java8 method referenced exampls:

  • Method references in Java 8 are compact, easy-to-read lambda expressions which will refer to an existing method. They can be used as an alternative to writing a lambda expression that simply calls an existing method
  • Method references will be accessed using double colon :: opearator

Method References Types:

  • Reference to a static method: Class::staticMethod
  • Reference to an instance method of a particular object: object::instanceMethod
  • Reference to an instance method of an arbitrary object of a particular type: Class::instanceMethod
  • Reference to a constructor: Class::new

Here’s an example that demonstrates using a method reference to sort a list of strings in ascending order:

//Sample Code 
List<String> words = Arrays.asList("apple", "banana", "cherry");

words.sort(String::compareTo);

System.out.println(words);
// Output: [apple, banana, cherry]

In this example, the method reference String::compareTo refers to the compareTo method of the String class, which compares two strings lexicographically. The sort method takes a Comparator object as an argument, and the method reference can be used to create an instance of Comparator that performs the sorting.

Here are some real-world examples of using method references in Java 8:

Sorting a list of objects:

//Person entity
List<Person> people = Arrays.asList(
  new Person("Jayaram", 25),
  new Person("Javasavvy", 30),
  new Person("Test", 20)
);

people.sort(Comparator.comparing(Person::getAge));

In this example, the method reference Person::getAge refers to the getAge method of the Person class, which returns the age of a person. The Comparator.comparing method takes a Function that extracts a Comparable from the objects being compared, and the method reference is used to create a Comparator that sorts the list of people based on their age.

Converting a list of strings to upper case:

List<String> words = Arrays.asList("apple", "banana", "cherry");

words = words.stream().map(String::toUpperCase).collect(Collectors.toList());

In this example, the method reference String::toUpperCase refers to the toUpperCase method of the String class, which returns a string in upper case. The map method of the stream takes a Function that transforms each element in the stream, and the method reference is used to create a Function that converts each string in the list to upper case.

Finding the maximum value in a list of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int max = numbers.stream().reduce(Integer.MIN_VALUE, Integer::max);

In this example, the method reference Integer::max refers to the max method of the Integer class, which returns the maximum of two integers. The reduce method of the stream takes an identity value and a BinaryOperator that combines two values, and the method reference is used to create a BinaryOperator that finds the maximum value in the list of integers.