Java 8供应商示例
时间:2020-02-23 14:34:54 来源:igfitidea点击:
在本教程中,我们将看到Java 8供应商接口。
供应商是函数接口,不会采取任何参数并产生结果
type T。
它具有一个函数方法,称为 T get()随着供应商是函数接口,因此它可以用作Lambda表达式的分配目标。
以下是Java 8供应商接口的源代码。
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
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Java 8供应商示例
让我们使用 supplier打印字符串的接口:
package org.igi.theitroad;
import java.util.function.Supplier;
public class Java8SupplierExample {
public static void main(String[] args) {
Supplier<String> supplier= ()-> "igi";
System.out.println(supplier.get());
}
}
它很简单使用 supplier interface要得到 String目的。
运行上面的程序时,我们将得到以下输出:
igi
让我们使用自定义类创建另一个例子 Student。
我们将使用供应商 supply new Student目的。
package org.igi.theitroad;
public class Student {
private int id;
private String name;
private String gender;
private int age;
public Student(int id, String name, String gender, int age) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";
}
}
现在让我们创造 Supplier将用于提供新的对象 Student目的。
package org.igi.code2master;
import java.util.function.Supplier;
public class Java8SupplierExample {
public static void main(String[] args) {
Supplier studentSupplier = () -> new Student(1, "igi", "M", 19);
Student student = studentSupplier.get();
System.out.println(student);
}
}
在流生成方法中使用供应商
如果我们观察到流生成方法的签名,我们会注意到它将供应商作为参数。
public static<T> Stream<T> generate(Supplier<T> s)
Stream's generate method返回A. infinite sequential stream供应商生成每个元素的地方。
假设我们希望在0到10之间生成5个随机数。
package org.igi.theitroad;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class Java8SupplierExample {
public static void main(String[] args) {
Supplier<Integer> randomNumbersSupp=() -> new Random().nextInt(10);
Stream.generate(randomNumbersSupp)
.limit(5)
.forEach(System.out::println);
}
}
正如你想要的那样,我们已经使用过 supplier作为 () -> new Random().nextInt(10)生成随机数。 limit(5)用于仅将流限制为5个元素,也使用Java 8 Foreach循环来打印流的元素。

