public class SupplierWithMethodReference { public static void main(String[] args) { Supplier<String> s1 = MyUtil::getFavoriteBook; System.out.println(s1.get());
MyUtil myUtil = new MyUtil(); Supplier<Integer> s2 = myUtil::getAge; System.out.println(s2.get()); Random random = new Random(); Supplier<Integer> s3 = random::nextInt; System.out.println(s3.get()); } }
class MyUtil { private Integer age = 30; public static String getFavoriteBook(){ return "Mahabharat"; } public Integer getAge(){ return age; } }
public class SupplierWithConstructorRef { public static void main(String[] args) { Supplier<Random> s1 = Random::new; Random random = s1.get(); System.out.println(random.nextInt(10)); Supplier<Book> s2 = Book::new; Book book = s2.get(); System.out.println(book.getBookName()); } }
class Book { private String bookName = "Mahabharat"; public String getBookName(){ return bookName; } }
public class SpecificDataTypeSupplier { public static void main(String[] args) { int age = 30; BooleanSupplier bs = () -> age > 20; System.out.println(bs.getAsBoolean()); Random random = new Random(); IntSupplier is = random::nextInt; System.out.println(is.getAsInt()); LongSupplier ls = random::nextLong; System.out.println(ls.getAsLong());
public class SupplierConsumerDemo { public static void main(String[] args) { Supplier<String> s = Country::getPMName; Consumer<String> c = Country::printMessage; c.accept(s.get()); } }
class Country { public static String getPMName() { return "Narendra Modi"; } public static void printMessage(String msg) { System.out.println(msg); } }