消费者 consumer
import org.junit.Test;
import java.util.function.Consumer;
public class consumer {
public void test02(Consumer<String> consumer){
consumer.accept("abc");
}
@Test
public void f1(){
test02(s -> System.out.println(s.length()));//3
test02(s -> System.out.println(s.toUpperCase()));//ABC
}
}
生产者 supplier
import java.util.function.Supplier;
public class supplier {
public User test01(java.util.function.Supplier<User> supplier){
return supplier.get();
}
@Test
public void f1(){
User user = test01(() -> new User(1,"张三",18));
User user2 = test01(() -> new User(2,"李四",19));
System.out.println(user);
System.out.println(user2);
}
}
断言 predicate
import org.junit.Test;
import java.util.function.Predicate;
public class predicate {
public boolean test02(Predicate<String> predicate){
return predicate.test("abc");
}
@Test
public void f1(){
test02(new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("a");
}
});
System.out.println(test02(s -> s.contains("a"))); //true
System.out.println(test02(s -> s.length() == 5));// false
}
}
转换 function
import org.junit.Test;
import java.util.function.Function;
public class function {
public Person test01(Function<String,Person> function){
return function.apply("宋宋");
}
@Test
public void f1(){
System.out.println(test01(s -> new Person(s)));
}
}
实体类 User
public class User {
private int id;
private String name;
private int 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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
实体类 Person
package com.example.函数式接口;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}