面试之前必须要了解的java8新特性

前言

java8新增了很多新的特性,今天就跟大家聊一聊函数式编程。

所谓的函数式编程,就是为了简化java8之前的匿名方法,提高java8的可读性。当然,提供了一些方法,可以更简便的去过滤、汇总集合数据。

oracle官网上的what‘s new上列出的下面几点:

  • Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.

    (java8的一个新的语言特性,Lambda表达式,在这个版本已经发布。他们让你把一个函数或者代码当成参数。Lambda表达式让你更简洁的表达单方法的实例。)

  • Method references provide easy-to-read lambda expressions for methods that already have a name.

    (方法引用为已命名的方法提供更易读的lambda表达式。)

  • Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaceshan.

    (默认方法允许像接口添加新功能,并且能兼容老版本的代码)

正文

FunctionaInterface

@FunctionaInterface是一个注解,表明接口是一个函数接口,可以用于lambda表达式。

其实默认只有一个方法的接口都是函数接口。

接口内如果出了一个接口方法外,其余的都是默认方法,那么这个接口同样是函数接口

interface Car {
	void run();
	default void start(){
		System.out.println("汽车默认的启动方法.");
	}
}

上面这个接口也是函数接口。

  • 函数式接口类型
    • 提供类型 - Supplier
    • 消费类型 - Consumer
    • 转换类型 - Function<T,R>
    • 断定类型 - Predicate
    • 隐藏类型 - Action

五种函数接口类型

  • Supplier

    对应没有入参,有返回值的匿名函数接口

    。下面是java里的接口定义:

    @FunctionalInterface
    public interface Supplier<T> {
    
        /**
         * Gets a result.
         *
         * @return a result
         */
        T get();
    }
    
    

    no bb,show code.

    public class SupplierDemo {
    
        public static void main(String[] args) {
            //getLongSupplier是把SupplierDemo的getLong方法抽象成一个变量
            Supplier<Long> getLongSupplier = SupplierDemo::getLong;
            //Supplier.get():调用get方法,并返回getLong方法的返回值
            System.out.println(getLongSupplier.get());
        }
    
    
        private static Long getLong(){
          return new Random().nextLong();
        }
    }
    
    

    其中 SupplierDemo::getLong 是java8的表示方法,这里可以理解成把getLong这个方法赋值给 getLongSupplier这个引用。

​ 真实的方法调用发生在下面一行,当getLongSupplier.get(),才真正的调用方法。

  • Consumer

对应有入参,没有返回值的函数接口

Consumer接口定义

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}
public class ConsumerDemo {

    public static void main(String[] args) {
        //抽象print函数
        Consumer<String> print = System.out::println;
        print.accept("print:Hello,World!");

        Consumer<String> print2 = System.out::println;
        print2.accept("print2:Hello,World");

        print.andThen(print2).accept("addThen:Hello,World");


    }
}

这里把System.out的println函数赋值给print这个方法指针。具体的方法调用发生在accept方法调用的时候。

addThen方法可以把多个Consumer串联启来。

print.andThen(print2).accept(“addThen:Hello,World”)执行的时候,先调用print,然后再调用print2.

  • Function<T,R>

对应有入参也有返回值的的函数接口

@FunctionalInterface
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);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

compose和addThen都是编排Function实例,

functionA.compose(functionB):表示先调用functionB,然后再调用functionA。

functionA。addThen(functionB):表示小调用functionAl,然后再调用functionB.

public class FunctionDemo {

    public static void main(String[] args) {
        Function<String,Long> stringToLong = Long::valueOf;
        System.out.println(stringToLong.apply("1"));

        Function<Long,String> longToString = String::valueOf;
        System.out.println(longToString.apply(1L));

        // "1" -> 1L -> "1"
        System.out.println(longToString.compose(stringToLong).apply("1"));

        // lL -> "1" -> 1L
        System.out.println(longToString.andThen(stringToLong).apply(1L));
    }


}
  • Action

隐藏类型:对应没有入参,也没有返回值的函数方法

public class ActionDemo {

    public static void main(String[] args) {
        //匿名内部类
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("execute run.");
            }
        };

        //函数式编程
        Runnable runnable1 = () -> {
            System.out.println("lamdba execute run.");
        };
    }
}
  • 断言类型

主要是用来做过滤用的函数接口

@FunctionalInterface
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);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

可以用来设计用来过滤的函数指针。

public class PredicatieDemo {

    public static void main(String[] args) {
    	//把isDir实例化成一个方法指针
        Predicate<File> perdicate = PredicatieDemo::isDir;
        //调用test判断一个文件是否为目录
        System.out.println(perdicate.test(new File("D:\\text.txt")));
    }

    public static boolean isDir(File file){
        return file.isDirectory();
    }
}

小结

函数式接口有五种,对应匿名函数里的不同方法。

Supplier对应 没有入参,有返回值的函数。

Consumer对应 有入参,没有返回值的函数。

Function对应有入参,有返回值的函数。

Action对应没有入参,没有返回值的函数。

Predicate可以用来做断言的方法指针。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值