这是供应商:
public Integer getInteger() { return new Random().nextInt();}这是消费者:
public void sum(Integer a, Integer b) { System.out.println(a + b);}因此,用通俗易懂的术语来说,供应商是一种返回一些值(如返回值)的方法。而使用者是一种消耗一些值(如在方法参数中)并对其执行一些操作的方法。
这些将转变为以下形式:
// new operator itself is a supplier, of the reference to the newly created objectSupplier<List<String>> listSupplier = ArrayList::new;Consumer<String> printConsumer = a1 -> System.out.println(a1);BiConsumer<Integer, Integer> sumConsumer = (a1, a2) -> System.out.println(a1 + a2);
至于用法,最基本的示例是:
Stream#forEach(Consumer)方法。它需要一个Consumer,它使用您要迭代的流中的元素,并对每个元素执行一些操作。大概打印出来。
Consumer<String> stringConsumer = (s) -> System.out.println(s.length());Arrays.asList("ab", "abc", "a", "abcd").stream().forEach(stringConsumer);


