Java 8 — Supplier | Code Factory
2 min readMay 5, 2020
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
- Supplier can be used to supply items(objects)
- Supplier won’t take any input and it will always supply objects
- Supplier Functional Interface contains only one method get()
@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
- 2, 4, 6, 8 places only digits
- 1, 3, 5, 7 only Capital Uppercase 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