Course contentsShow
← Java
Lesson 1668 of 2,87035. Functional InterfacesFree lesson

Method References as Suppliers

Using method references like String::new or System::currentTimeMillis as Suppliers.

Method References as Suppliers

You'll learn: How to use method references like String::new and System::currentTimeMillis as concise Supplier implementations.

The Core Idea

You've seen how lambdas can implement Supplier<T>, like () -> new String() or () -> System.currentTimeMillis(). But when your lambda simply calls a method without arguments, Java offers a cleaner syntax: method references. These act as perfect Supplier implementations because both take no parameters and return a value.

Common Method Reference Patterns

Constructor References

When your Supplier just creates a new object:

// Lambda version
Supplier<String> lambda = () -> new String();

// Method reference version
Supplier<String> supplier = String::new;

String result = supplier.get(); // Returns new empty String

The ClassName::new syntax references the constructor as a Supplier.

Static Method References

When a static method takes no arguments and returns something:

// Lambda version
Supplier<Long> lambdaTime = () -> System.currentTimeMillis();

// Method reference version
Supplier<Long> timeSupplier = System::currentTimeMillis;

Long timestamp = timeSupplier.get(); // Returns current time in milliseconds

Why Use Method References?

Think of method references as shortcuts—when your lambda's sole job is to call one method, the method reference removes the ceremonial () -> syntax. Your code becomes more readable: String::new clearly says "supply new Strings," while () -> new String() adds visual noise.

Key Takeaway: Method references like String::new (constructors) and System::currentTimeMillis (static methods) elegantly replace lambdas that simply call a single no-argument method, making your Supplier implementations cleaner and more expressive.