HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java 8 method reference example

Java 8 method reference example

In Java 8, we can refer a method from class or object using class::methodName type syntax. Let’s learn about different types of available method references in java 8.

Table of Contents

1. Types of Method References
2. Reference to static method - Class::staticMethodName
3. Reference to instance method from instance - ClassInstance::instanceMethodName
4. Reference to instance method from class type - Class::instanceMethodName
5. Reference to constructor - Class::new

1. Types of method references

Java 8 allows four 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

3. Method reference to instance method from instance – ClassInstance::instanceMethodName

In above example, we use System.out.println(value) to print the max value found. We can use System.out::println to print the value.

List<Integer> integers = Arrays.asList(1,12,433,5);
		
Optional<Integer> max = integers.stream().reduce( Math::max ); 

max.ifPresent( System.out::println ); 

Output:

433

4. Method reference to instance method from class type – Class::instanceMethodName

In this example, s1.compareTo(s2) is referred as String::compareTo.

List<String> strings = Arrays
		.asList("how", "to", "do", "in", "java", "dot", "com");

List<String> sorted = strings
		.stream()
		.sorted((s1, s2) -> s1.compareTo(s2))
		.collect(Collectors.toList());

System.out.println(sorted);

List<String> sortedAlt = strings
		.stream()
		.sorted(String::compareTo)
		.collect(Collectors.toList());

System.out.println(sortedAlt);

Output:

[com, do, dot, how, in, java, to]
[com, do, dot, how, in, java, to]

5. Reference to constructor – Class::new

The first method can be updated to create a list of integers from 1 to 100. Using lambda expression is rather easy. To create a new instance of ArrayList, we have use ArrayList::new.

List<Integer> integers = IntStream
				.range(1, 100)
				.boxed()
				.collect(Collectors.toCollection( ArrayList::new ));

Optional<Integer> max = integers.stream().reduce(Math::max); 

max.ifPresent(System.out::println); 

Output:

99

That’s 4 type of method references in java 8 lambda enhancements.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Debraj

    March 7, 2019

    ArrayList::new equivalent to new ArrayList() this is not correct this applicable only if “The target type of this expression must be a functional interface”

    • Debraj

      March 7, 2019

      I meant not always correct there is a condition.

  2. Chetan Patel

    April 12, 2018

    Consumer con = System.out::println;
    con.accept(“Hello”);

  3. thangamma

    February 14, 2018

    How do you come to know about the parameters that are taken by these static methods.

    For Example:
    If I want to write System.out.println(“Hello”);
    How do i write it using method reference ?

    • Chetan Patel

      April 12, 2018

      Consumer con = System.out::println;
      con.accept(“Hello”);

    • satak

      November 27, 2019

      System.out::println

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces