JDK8辅助学习(二):Lambda表达式----常用的内置函数式接口

前言

        当你在学习本文时,如果您还不了解 Lambda表达式的使用,请先跳转链接:JDK8新特性(一):Lambda表达式 ,来了解一下 Lambda表达式的基本使用。

        从 Lambda表达式 一文,我们了解到使用Lambda表达式的前提条件,如下图所示。

       由于使用条件的限制,明显不利于 Lambda表达式 的推广使用。为了能够让我们更方便的使用 Lambda 表达式,JDK为我们提供了大量的内置函数式接口。

内置函数式接口

       它们都位于 java.util.function 包中,如下图所示。

          

       常用的四大核心内置函数式接口,如上图所示。分别是 ①Supplier   ②Consumer  ③Function  ④Predicate ,接下来我们来分别介绍这四大核心内置函数式接口

1.Supplier

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

  我们重点来看一下 get() 方法(Supplier也就这一个抽象方法)。

  特点:①无参数     ②有返回值     --------->这种无参数 有返回值的接口,称之为"供给性接口"

  Demo:

       使用 Supplier接口作为方法参数类型,通过 Lambda表达式 来求出 int 数组中的最大值。

/**
 * 利用 Supplier接口 1.无参 2.有返回值 特性,返回数组最大值
 */
public class SupplierDemo{
    
    public static void main(String[] args){
        int max = printMax(()->{
            int[] arr = {19,63,15,84,56,38};
            Arrays.sort(arr);//默认为升序排序
            return arr[arr.length-1];
        });
        System.out.println("数组最大值为:"+max);
    }

    public static int printMax(Supplier<Integer> supplier){
        int max = supplier.get();//通过supplier.get() 方法,获得返回值
        return max;
    }
}

2.Consumer

@FunctionalInterface
public interface Consumer<T> {

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

  我们重点来看一下 accept() 方法(该接口还有一个 andThen()方法)。

  特点:①有参数     ②无返回值     --------->这种有参数 无返回值的接口,称之为"消费性接口"

  Demo:

     ①使用 Consumer 接口作为方法参数类型,通过 Lambda表达式 来将传入的"Hello Lambda"字母转为小写。

/**
 * 利用 Consumer接口 1.有参 2.无返回值 特性,将传入字母转为全小写
 */
public class ConsumerDemo{

    public static void main(String[] args){
        printLower((String str)->{
            String lower = str.toLowerCase();
            System.out.println("转为小写为:"+lower);
        });

        //简写如下:
        //printLower(str->System.out.println("转为小写为:"+str.toLowerCase()));
    }

    public static void printLower(Consumer<String> consumer){
        consumer.accept("Hello Lambda");
    }

}

     ②将传入的"Hello Lambda"字母先转为小写,再转为大写(此处使用 andThen() 方法更精简

public class ConsumerDemo{

    public static void main(String[] args){
        printLower((String str)->{
            String lower = str.toLowerCase();
            System.out.println("转为小写为:"+lower);
        },(String str)->{
            String upper = str.toUpperCase();
            System.out.println("转为大写为:"+upper);
        });  
    }

    public static void printLower(Consumer<String> c1,Consumer<String> c2){
        String str = "Hello Lambda";
        c1.accept(str);
        c2.accept(str);
    }
}

     先转为小写,再转为大写,使用 andThen 精简版,如下所示

public class ConsumerAndThenDemo{

    public static void main(String[] args){
       printLower(str->System.out.println("转为小写为:"+str.toLowerCase()),str->System.out.println("转为大写为:"+str.toUpperCase()));
    }

    public static void printLower(Consumer<String> c1,Consumer<String> c2){
        String str = "Hello Lambda";
        c1.andThen(c2).accept(str);
    }
}

3.Function

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

  我们重点来看一下 apply() 方法(该接口还有一个 andThen()、identify()、compose()方法)。

  特点:①有参数     ②有返回值     --------->这种有参数 有返回值的接口,称之为"类型转换接口"

  Demo:

     ①使用 Function 接口作为方法参数类型,通过 Lambda表达式 来将传入的"Hello Lambda"字母转为小写,并返回。

/**
 * 利用 Function接口 1.有参 2.有返回值 特性,将传入字母转为小写,并返回
 */
public class FunctionDemo{

    public static void main(String[] args){
        String lower = showLower(str->str.toLowerCase());
        System.out.println("转为小写为:"+lower);
    }

    public static String showLower(Function<String,String> function){
        String resVal = function.apply("Hello Lambda");
        return resVal;
    }

}

     ②传入一个 String 类型值,将其转换为 Integer 类型,并将返回值 * 5,再次返回(此处使用andThen()方法)

/**
 * andThen() 方法,简写版
 */
public class FunctionAndThenDemo{

    public static void main(String[] args){
        int num = printNum(str->Integer.parseInt(str),str->str*5);
        System.out.println("转为Integer,*5后为:"+num);
    }

    public static Integer printNum(Function<String,Integer> f1,Function<Integer,Integer> f2){
    Integer num = f1.andThen(f2).apply("10");
    return num;
    }
}

4.Predicate

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

     我们重点来看一下 test() 方法(该接口还有一个 and()、or()、negate()、isEqual()方法)。

     特点:①有参数     ②返回 bollean值     --------->这种 返回 bollean 类型 接口,就是用来做判断的。

  Demo:

     ①使用 Predicate 接口作为方法参数类型,通过 Lambda表达式 来判断 传入的值是否大于10,并返回 true/false

/**
 * 利用 Predicate接口 1.有参 2.返回值为boolean 特性,将传入参数与20进行比较,并返回true/false
 */
public class PredicateDemo{

    public static void main(String[] args){
        boolean flag = flag(num->num > 20);
        System.out.println("传入值是否大于20:"+flag);
    }

    public static boolean flag(Predicate<Integer> predicate){
        boolean flag = predicate.test(15);
        return flag;
    }
}

     判断传入参数包含H,同时包含 W(使用 and()方法更精简,如下所示)

public class PredicateDemo{

    public static void main(String[] args){
        boolean flag = flag(str->str.contains("H"),str->str.contains("W"));
        if(flag){
            System.out.println("包含H,同时包含W");
        }else{
            System.out.println("Ohters...");
        }
    }

    public static boolean flag(Predicate<String> p1,Predicate<String> p2){
        String str = "Hello World";
        boolean flag1 = p1.test(str);
        boolean flag2 = p2.test(str);
        if(flag1 && flag2){
            return true;
        }else{
            return false;
        }
    }
}

     使用and()方法判断传入参数包含H,同时包含 W

public class PredicateDemo{

    public static void main(String[] args){
        boolean flag = flag(str->str.contains("H"),str->str.contains("W"));
        if(flag){
            System.out.println("包含H,同时包含W");
        }else{
            System.out.println("Ohters...");
        }
    }

    public static boolean flag(Predicate<String> p1,Predicate<String> p2){
        String str = "Hello orld";
        boolean flag = p1.and(p2).test(str);
        if(flag){
            return true;
        }else{
            return false;
        }
    }
}

     使用 or()方法、negate()方法   同 与或非

        negate() 方法就是非的意思。本文就不在此处过多的介绍 or()方法negate()方法 的使用了


附:JDK8新特性(目录)

    本目录为 JDK8新特性 学习目录,包含JDK8 新增全部特性的介绍。

    如需了解,请跳转链接查看:我是跳转链接


四大核心内置函数式接口,就介绍到这里了

如果本文对你有所帮助,那就给我点个赞呗 ^_^ 

End

发布了247 篇原创文章 · 获赞 44 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/lzb348110175/article/details/103860323