就像名字一样,他它只是一个供应商,他它的任务很简单,给你供货。
Supplier Functional Interface只实现定义了一个方法:get
package java.util.function;/*** Represents a supplier of results.** <p>There is no requirement that a new or distinct result be returned each* time the supplier is invoked.** <p>This is a <a href="package-summary.html">functional interface</a>* whose functional method is {@link #get()}.** @param <T> the type of results supplied by this supplier** @since 1.8*/@FunctionalInterfacepublic interface Supplier<T> {/*** Gets a result.** @return a result*/T get();}
就像下面的例子,供应商每次都给你提供一个有一个handsome xiaohundun的Map
package other;/** @author chou* @Description* @since 2020/1/13**/import org.junit.Test;import java.util.HashMap;import java.util.Map;import java.util.function.Supplier;public class SupplierTest {@Testpublic void supplierFi () {// Supplier<Map<Object,Object>> emptyMap = Collections::emptyMap;// Map<Object, Object> mmmmmmamaipi = emptyMap.get();// System.out.format("%3$s size %1$x ,hashcode %2$x", mmmmmmamaipi.size(), mmmmmmamaipi.hashCode(), "mmmmmmamaipi");Supplier<Map<String,String>> handsomeMap = ()->{Map<String,String> rm = new HashMap<>();rm.put("xiaohundun", "handsome");return rm;};Map<String,String> handsomeMap1 = handsomeMap.get();System.out.format("xiaohundun is %s %n", handsomeMap1.get("xiaohundun"));handsomeMap1.put("xiaohundun", "kind");Map<String,String> handsomeMap2 = handsomeMap.get();System.out.format("xiaohundun is %s", handsomeMap2.get("xiaohundun"));}}
Supplier FI在流中的应用:
IntStream.generate接收一个IntSupplier,此Supplier提供数字,中间peek了一下用来虚区,然后用短路操作终结流。
@Testpublic void generate () {#An infinite stream should be ended by short-circuiting operations such as limit & anyMatch & findFirst etc.System.out.println(IntStream.generate(() -> (int) (Math.random() * 100)).peek(System.out::println).anyMatch((i) -> i == 6));}
Supplier FI在非流中的应用:
ThreadLocal有一个静态内部类,它集成继承了ThreadLocal,并且内部绑定了Supplier。ThreadLocal提供了withInitial方法用来创建一个包含初始值的ThreadLocal,当你使用ThreadLocal#get方法的时候会检查线程绑定Map是否为空,如果为空进行值的初始化并绑定Thread与ThreadLocalMap,如果不为空返回ThreadLocalMap中的值。
@Testpublic void supplierThreadLocal(){Supplier<String> supplierTheadLocal = () -> "xiaohundun";ThreadLocal<String> threadLocal = ThreadLocal.withInitial(supplierTheadLocal);System.out.println(threadLocal.get());}
@Testpublic void Optional () {OptionalInt value = OptionalInt.empty();try {value.orElseThrow(new Supplier<Throwable>() {@Overridepublic Throwable get () {return new ArithmeticException("哈哈");}});} catch (Throwable e) {System.out.println(e.getMessage());}value.orElseGet(new IntSupplier() {@Overridepublic int getAsInt () {return 66;}});}
