Java 8 — Supplier | Code Factory

Index Page : Link

Reference Link : Link

Donate : Link

Sometimes our requirement is we have to get some value based on some operation like

supply Student object

Supply Random Name

Supply Random OTP

Supply Random Password

etc

  • For this type of requirements we should go for Supplier
@FunctionalInterface
public interface Supplier<T> {
T get();
}

Supplier Functional interface does not contain any default and static methods.

Program to generate random name :

package com.codeFactory.supplier;import java.util.function.Supplier;public class Test {
public static void main(String... args) {
Supplier<String> s = () -> {
String[] s1 = {"Narendra", "Amit", "Yogi", "Rahul"};
int x = (int) (Math.random() * 4);
return s1[x];
};

System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
}
}

Output :

Narendra
Amit
Rahul

Program to get System Date by using Supplier :

package com.codeFactory.supplier;import java.util.Date;
import java.util.function.Supplier;
public class Test {
public static void main(String... args) {
Supplier<Date> s = () -> new Date();
System.out.println(s.get());
}
}

Output :

Wed Apr 29 13:27:58 IST 2020

Program to generate 5 digit random OTP :

package com.codeFactory.supplier;import java.util.function.Supplier;public class Test {
public static void main(String... args) {
Supplier<String> otp = () -> {
String s = "";
for(int i=0; i<5; i++) {
s = s + (int) (Math.random() * 10);
}
return s;
};

System.out.println(otp.get());
System.out.println(otp.get());
System.out.println(otp.get());
}
}

Output :

33325
89449
53473

Program to generate random password :

Rules :

  • length should be 8 characters
package com.codeFactory.supplier;import java.util.function.Supplier;public class Test {
public static void main(String... args) {
Supplier<String> s = () -> {
String symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#$@";
Supplier<Integer> d = () -> (int)(Math.random() * 10);
Supplier<Character> c = () -> symbols.charAt((int)(Math.random() * 29));
String psw = "";
for(int i=0; i<8; i++) {
if(i%2 == 0) {
psw += d.get();
} else {
psw += c.get();
}
}
return psw;
};
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
}
}

Output :

9V3#4I7R
7I9Z2Q5$
8D8N0Z3A

Comparison Table of Predicate, Function, Consumer and Supplier :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store