四大函数式接口

197 阅读1分钟

Function函数型接口

public interface Function<T, R> {
    /**
     * Applies this function to the given argument
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}
// 只要是函数型接口就可以使用lambda表达式
public class test1 {
    public static void main(String[] args) {
      Function function = new Function<String, String>() {
           @Override
          public String apply(String str) {
              return str;
           }
        };
        //lambda表达式
        Function<String,String> function = (str)->{return str;};       
        System.out.println(function.apply("asdf"));
    }
}

Predicate判断型接口

public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}
public class test2 {
    public static void main(String[] args) {
       Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.isEmpty();
            }
        };

        Predicate<String> predicate = (string)->{
            return string.isEmpty();
        };
        System.out.println(predicate.test("hello"));        //false
    }
}

Consumer消费型接口

public interface Consumer<T> {
    /**
     * Performs this operation on the given argument.
     * @param t the input argument
     */
    void accept(T t);
}
public class test3 {
    public static void main(String[] args) {
       Consumer<String> consumer = new Consumer<String>() {
           @Override
           public void accept(String s) {
               System.out.println(s);
          }
       };

        Consumer<String> consumer = (string)->{
            System.out.println(string);
        };
        consumer.accept("hello");
    }
}

Supplier供给型接口

public interface Supplier<T> {
    /**
     * Gets a result.
     * @return a result
     */
    T get();
}
public class test4 {
    public static void main(String[] args) {
        Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {
                return "1024";
            }
        };
        Supplier<String> supplier = ()->{
            return "1024";
        };
        System.out.println(supplier.get());
    }
}

总结

public class ConsumerPractice {
    public static void main(String[] args) {
        Consumer<String> a=b-> System.out.println(b);
        a.accept("hello");

        Function<Integer,String> ad=b->b.toString();
        System.out.println(ad.apply(11));


        Predicate<String> ac=b->b.isEmpty();
        System.out.println(ac.test("hello"));

        Supplier<String> ae= ()-> "a";
        System.out.println(ae.get());
    }
}