badCoder badCoder - 1 month ago 6
Java Question

When we should use Supplier in Java 8?

What difference between this code?

Supplier<LocalDate> s1 = LocalDate::now;
LocalDate s2 = LocalDate.now();

System.out.println(s1.get()); //2016-10-25
System.out.println(s2); //2016-10-25


I start learning functional interfaces in Java 8 and don't understand which benefit provides Supplier. When and how, exactly, we should use him. Does Supplier improve performance or maybe the benefits on abstraction level?

Thanks for your answers! And it isn't duplicate question because I used search and didn't find what I need.

UPDATE 1:
You mean this?

Supplier<Long> s1 = System::currentTimeMillis;
Long s2 = System.currentTimeMillis();

System.out.println(s1.get()); //1477411877817
System.out.println(s2); //1477411877817
try {
Thread.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(s1.get()); //1477411880817 - different
System.out.println(s2); //1477411877817

Answer

It definitely doesn't improve the performance. Your question is similar to this one: Why are we using variables? We could simply just recalculate everything every time we need it. Right?

If you need to use a method a lot of times, but it has a wordy syntax.

Let's assume you have a class named MyAmazingClass, and you have a method in it with the name MyEvenBetterMethod (which is static), and you need to call it 15 times at 15 different positions in your code. Of course, you can do something like...

int myVar = MyAmazingClass.MyEvenBetterMethod();
// ...
int myOtherVar = MyAmazingClass.MyEvenBetterMethod();
// And so on...

...but you can also do

Supplier<MyAmazingClass> shorter = MyAmazingClass::MyEvenBetterMethod;

int myVar = shorter.get();
// ...
int myOtherVar = shorter.get();
// And so on...