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.
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
Book
- a POJO class with getters and setters. You can replace the class with Javarecord
, also.BookRepository
- for database transactions.BookRepositoryImpl
- An implementation class that injects fake data.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.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.