Java 8 - Method References


In Java 8, we can refer a method from class or object using class::methodName type syntax.

A method reference can be used to point the following types of methods −

  • Static methods
  • Instance methods
  • Constructors using new operator (TreeSet::new)

1 Types of method references

Method ReferenceDescriptionMethod reference example
Reference to static methodUsed to refer static methods from a classMath::max equivalent to Math.max(x,y)
Reference to instance method from instanceRefer to an instance method using a reference to the supplied objectSystem.out::println equivalent to System.out.println(x)
Reference to instance method from class typeInvoke the instance method on a reference to an object supplied by the contextString::length equivalent to str.length()
Reference to constructorReference to a constructorArrayList::new equivalent to new ArrayList()

2. Method reference to static method – Class::staticMethodName

An example to use Math.max() which is static method.

List<Integer> integers = Arrays.asList(1,12,433,5);
         
Optional<Integer> max = integers.stream().reduce( Math::max );
 
max.ifPresent(value -> System.out.println(value));

Output:

433





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition