Skip to content

Reference to Static Method (Method References)

In this lesson, you will learn about the first kind of method reference, "a reference to static methods". You will be introduced to a complex object method reference with example snippets and explanations.

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

What is a reference to static methods mean?

A static method reference refers to the static method for a class. We can use a method reference to call the static methods directly.

Syntax

The syntax for referencing a static method is as follows.

ClassName::staticMethodName

Example

Let us write a simple example that contains four files

  1. Book - a POJO class with getters and setters. You can replace the class with Java record , also.
  2. BookRepository - for database transactions.
  3. BookRepositoryImpl - An implementation class that injects fake data.
  4. ReferenceToStaticMethod - This is where the actual magic happens.

Code

public class Book {
  private final String title;
  private final String author;
  private final int year;
  private final int copiesSoldInMillions;
  private final double rating;
  private final double costInEuros;

  public Book(
      String title,
      String author,
      int year,
      int copiesSoldInMillions,
      double rating,
      double costInEuros) {
    this.title = title;
    this.author = author;
    this.year = year;
    this.copiesSoldInMillions = copiesSoldInMillions;
    this.rating = rating;
    this.costInEuros = costInEuros;
  }

  public Double getCostInEuros() {
    return costInEuros;
  }

  public double getRating() {
    return rating;
  }

  public String getTitle() {
    return title;
  }

  @Override
  public String toString() {
    return "commons.Book{ title="
        + title
        + ", author="
        + author
        + ", copiesSoldInMillions="
        + copiesSoldInMillions
        + ", costInEuros="
        + costInEuros
        + "}";
  }
}
import java.util.List;

public interface BookRepository {
  List<Book> getAllBooks();
}
import java.util.Arrays;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {

  @Override
  public List<Book> getAllBooks() {
    return Arrays.asList(
        new Book("Don Quixote", "Miguel de Cervantes", 1605, 500, 3.9, 9.99),
        new Book("A Tale of Two Cities", "Charles Dickens", 1859, 200, 3.9, 10.0),
        new Book("The Lord of the Rings", "J.R.R. Tolkien", 2001, 150, 4.0, 12.50),
        new Book("The Little Prince", "Antoine de Saint-Exupery", 2016, 142, 4.4, 5.0),
        new Book("The Dream of the Red Chamber", "Cao Xueqin", 1791, 100, 4.2, 10.0));
  }
}
import java.util.List;

public class ReferenceToStaticMethod {

  public static int compareByTitle(Book first, Book second) {
    return first.getTitle().compareTo(second.getTitle());
  }

  public static int compareByCost(Book first, Book second) {
    return first.getCostInEuros().compareTo(second.getCostInEuros());
  }

  public static void main(String[] args) {
    BookRepositoryImpl bookRepositoryImpl = new BookRepositoryImpl();

    // Inflate fake books
    List<Book> books = bookRepositoryImpl.getAllBooks();

    // Sort based on price
    System.out.println("SORT BASED ON PRICE: ");
    books.sort(ReferenceToStaticMethod::compareByCost);
    books.stream()
        .map(book -> book.getTitle() + " -> " + book.getCostInEuros())
        .forEach(System.out::println);

    
    System.out.println("---------");

    // Sort based on price
    System.out.println("SORT BASED ON TITLES: ");
    books.sort(ReferenceToStaticMethod::compareByTitle);
    books.stream()
        .map(book -> book.getTitle() + " -> " + book.getRating())
        .forEach(System.out::println);
  }
}

Explanation

Book, BookRepository, and BookRepositoryImpl files are self-explanatory. So let's see whats happening in ReferenceToStaticMethod class.

Lines 5 to 7 contain a static method compareByTitle(), which sorts the list of Book objects based on title.

Lines 9 to 11 contain a static method compareByCost(), which sorts the list of Book objects based on costInEuros per each book.

In line 14, we created an instance of BookRepositoryImpl class. We use this reference instance to call .getAllBooks() the method in line 17 to load the fake data into a collection of objects List<Book>.

Line 20 and 28 contains we are calling the static methods we declared inside the class to sort the list of Book objects.

The following explanation is the same for code snippet lines from "21 to 23" and "29 to 31".

On line 21, we chained the collection of book objects stored in books variable with .stream(), which converts all the collections of Book objects into a Stream of Book objects.

Line 22 contains an intermediate stream operation .map(...) forms stream of Book objects based on the parameters that are included inside the method, in this case title and costInEuros.

Line 23 contains a simple .forEach a terminal operation for printing elements on the console.

Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.