2.4.  Develop code that uses the Supplier interface

[Note]

The java.util.function.Supplier<T> is a functional interface in Java 8, with one abstract method named T get() that returns an instance of T. In other words, this is a factory that keeps on giving without expecting anything as input.


package java.util.function;

@FunctionalInterface
public interface Supplier<T extends Object> {

    public T get();

}
					

In the most basic form a Supplier will return an instance. For example, we could implement Supplier<Book> to return an instance of Book, like so:


public class Book {
    String title;
    String author;

    public Book(String t, String a) {
        title = t;
        author = a;
    }

    public String toString() {
        return title + " by " + author;
    }
}

...
...
Supplier<Book> s1 = () -> new Book("WSD 6 Guide", "Mikalai Zaikin");
Supplier<Book> s2 = () -> { return new Book("Java 8 Upgrade Guide", "Mikalai Zaikin"); };

System.out.println(s1.get());
System.out.println(s2.get());

					

output:

WSD 6 Guide by Mikalai Zaikin
Java 8 Upgrade Guide by Mikalai Zaikin
					

Alternatively, we could use a constructor reference (T::new) instead of the traditional (new T()) syntax to instantiate an instance. A constructor reference is much like a method reference, except it is a reference to a constructor instead of a method. We can use a constructor reference anywhere a lambda expression does nothing more than instantiate an instance. The only limitation with Supplier that constructor must take no arguments. For example:


public class Book {
    String title;
    String author;

    public Book() {
        title = "Default title";
        author = "Default author";
    }

    public String toString() {
        return title + " by " + author;
    }
}
...
...
Supplier<Book> s1 = Book::new;
System.out.println(s1.get());

					

output:

Default title by Default author
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz