Table des matières
Le Tutoriel de Java Supplier
View more Tutorials:


Dans Java 8, Supplier est une functional interface simple représentant une opération qui fournit une valeur à chaque appel. Supplier dispose d'une seule méthode get() et n'a pas de méthode par défaut.
Supplier
@FunctionalInterface
public interface Supplier<T> {
T get();
}
Il exsite certaines functional interfaces similaires qui fournissent les valeurs primitives: IntSupplier, DoubleSupplier, LongSupplier, BooleanSupplier:
IntSupplier int getAsInt();
DoubleSupplier double getAsDouble();
LongSupplier long getAsLong();
BooleanSupplier boolean getAsBoolean();
Exemple: Utiliser Supplier pour renvoyer un numéro aléatoire à chaque appel.
SupplierEx1.java
package org.o7planning.ex;
import java.util.function.Supplier;
public class SupplierEx1 {
public static void main(String[] args) {
Supplier<Double> random = () -> Math.random();
System.out.println("Random value: " + random.get());
System.out.println("Random value: " + random.get());
System.out.println("Random value: " + random.get());
}
}
Output:
Random value: 0.5085772031422864
Random value: 0.666568263619468
Random value: 0.18177402871597048
Example: Utiliser Supplier pour renvoyer à la date actuelle:
SupplierEx2.java
package org.o7planning.ex;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;
public class SupplierEx2 {
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
Supplier<LocalDateTime> s = () -> LocalDateTime.now();
LocalDateTime time = s.get();
System.out.println(time);
Supplier<String> s1 = () -> dtf.format(LocalDateTime.now());
String time2 = s1.get();
System.out.println(time2);
}
}
Output:
2021-02-12T13:31:43.023203
2021-02-12 13:31:43
Exemple: Utiliser Supplier dans la méthode statique Stream.generate pour imprimer cinq numéros aléatoires:
// Method of java.util.stream.Stream class:
static <T> Stream<T> generate(Supplier<T> s)
SupplierEx3.java
package org.o7planning.ex;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class SupplierEx3 {
public static void main(String[] args) {
// Returns a random integer in range [0,10)
Supplier<Integer> randomNumbersSupp = () -> new Random().nextInt(10);
Stream.generate(randomNumbersSupp)
.limit(5)
.forEach(System.out::println); // .forEach(Consumer)
}
}
Output:
5
5
0
2
0
Ci-dessous la liste de méthodes dans le package java.util utilisant Supplier:
Modifier and Type | Method and Description |
---|---|
T | Optional.orElseGet(Supplier<? extends T> other) |
<X extends Throwable> T |
Optional.orElseThrow(Supplier<? extends X> exceptionSupplier) |
<X extends Throwable> long |
OptionalLong.orElseThrow(Supplier<X> exceptionSupplier) |
<X extends Throwable> double |
OptionalDouble.orElseThrow(Supplier<X> exceptionSupplier) |
<X extends Throwable> int |
OptionalInt.orElseThrow(Supplier<X> exceptionSupplier) |
static <T> T | Objects.requireNonNull(T obj, Supplier<String> messageSupplier) |
Si une méthode qui ne prend pas de paramètre et renvoie une valeur, sa référence sera considérée comme un Supplier.
SupplierEx4.java
package org.o7planning.ex;
import java.time.LocalDate;
import java.util.function.Supplier;
public class SupplierEx4 {
public static void main(String[] args) {
Supplier<Integer> s1 = MyUtils::getCurrentYear; // Method reference
System.out.println(s1.get());
Employee employee = new Employee("Tom");
Supplier<String> s2 = employee::getName; // Method reference
System.out.println(s2.get());
}
public static class MyUtils {
public static int getCurrentYear() {
return LocalDate.now().getYear();
}
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
}
Output:
2021
Tom
Un Constructor créera un nouvel objet. S'il n'a pas de paramètre, donc sa référence est considérée comme un Supplier.
SupplierEx7.java
package org.o7planning.ex;
import java.util.Random;
import java.util.function.Supplier;
public class SupplierEx7 {
public static void main(String[] args) {
Supplier<Random> s = Random::new; // Constructor reference
//
int randomValue = s.get().nextInt(10);
System.out.println("Random Value: " + randomValue);
}
}
Output:
Random Value: 8