函数式接口

接口中只有一个抽象方法的口,称为函数式接口,可以使用注解@FunctionInterface 修饰
@FunctionInterface : 可以检查接口是否为函数式接口

内置四大核心函数式接口

Consumer 消费型接口

void accept(T t);

  1. @Test
  2. public void test5(){
  3. happy("hello world", str -> System.out.println("this is " + str));
  4. }
  5. public void happy(String str, Consumer<String> consumer){
  6. consumer.accept(str);
  7. }

image.png

Supplier 供给型接口

T get();

@Test
public void test6(){
    List<Integer> num = getNum(10, () -> (int) (Math.random() * 100));
    num.forEach(System.out::println);
}

public List<Integer> getNum(int num, Supplier<Integer> supplier){
    ArrayList<Integer> integers = new ArrayList<>();
    for (int i = 0; i < num; i++) {
        integers.add(supplier.get());
    }
    return integers;
}

image.png

Function 函数型接口

R apply(T t);

@Test
public void test7(){
    String hello_world = stringHandler("hello world", s -> s.substring(0, 5));
    System.out.println(hello_world);
}

public String stringHandler(String string, Function<String,String> function){
    return function.apply(string);
}

image.png

Predicate 断言型接口

boolean test(T t);

@Test
public void test8(){
    boolean query = isQuery("select query", s -> s.equals("select query"));
    System.out.println(query);
}

public boolean isQuery(String string, Predicate<String> predicate){
    return predicate.test(string);
}

image.png

其他接口

image.png