February 2020
Intermediate to advanced
412 pages
9h 36m
English
Lambda expressions can also implement methods that return items. For instance, the Supplier interface introduced in Java 8 (and originally introduced in Google Guava) has an abstract get() method that returns a T item for a given Supplier<T>. If we have a Supplier<List<String>> whose get() method returns List<String>, we can implement it using an old-fashioned anonymous class as follows:
import java.util.ArrayList;import java.util.List;import java.util.function.Supplier;public class A_05 { public static void main(String[] args) { Supplier<List<String>> listGenerator = new Supplier<List<String>>() { @Override public List<String> get() { return new ArrayList<>(); } }; List<String> myList = listGenerator.get(); }
Read now
Unlock full access