java基础---->java8中的函数式接口

时间:2021-09-02 19:07:15

  这里面简单的讲一下java8中的函数式接口,Function、Consumer、Predicate和Supplier。

 

函数式接口例子

一、Function:接受参数,有返回参数

package com.linux.huhx.function;

import java.util.function.Function;

public class FunctionDemo {

  private static int operateValue(int value, Function<Integer, Integer> function) {
    return function.apply(value);
  }

  private static int operateValue(int value, Function<Integer, Integer> srcFunc, Function<Integer, Integer> destFunc) {
    return srcFunc.andThen(destFunc).apply(value);
  }

  public static void main(String[] args) {
    int value = 10;
    int innerResult = operateValue(value, new Function<Integer, Integer>() {
      @Override
      public Integer apply(Integer t) {
        return 20 + t;
      }
    });
    System.out.println(innerResult); // 30

    int lambdaResult = operateValue(value, t -> t + 20);
    System.out.println(lambdaResult); // 30

    int andThenResult = operateValue(value, val -> val + 20, val -> val + 30);
    System.out.println(andThenResult); // 60
  }
}

 

二、Consumer:接受参数,没有返回

package com.linux.huhx.function;

import java.util.function.Consumer;

public class ConsumerDemo {

  private static void printValue(String value, Consumer<String> consumer) {
    consumer.accept(value);
  }

  public static void main(String[] args) {
    printValue("huhx", s -> System.out.println(s.toUpperCase())); // HUHX
  }
}

 

三、Predicate:接受参数,返回boolean

package com.linux.huhx.function;

import java.util.function.Predicate;

public class PredicateDemo {

  private static boolean predicateValue(int value, Predicate<Integer> predicate) {
    return predicate.test(value);
  }

  public static void main(String[] args) {
    System.out.println(predicateValue(17, x -> x >= 18)); // false
  }
}

 

四、Supplier:不接受参数,有返回值

package com.linux.huhx.function;

import java.util.function.Supplier;
import org.springframework.util.StringUtils;

public class SupplierDemo {

  private static String getOrDefault(String value, Supplier<String> supplier) {
    return StringUtils.isEmpty(value) ? supplier.get() : value;
  }

  public static void main(String[] args) {
    String name = "";
    System.out.println(getOrDefault(name, () -> "huhx")); // huhx
  }
}

 

友情链接