小滴课堂-学习笔记:(4) Java高级核心玩转JDK8 函数式编程

56 篇文章 0 订阅
14 篇文章 0 订阅

logo 愿景:"让编程不再难学,让技术与生活更加有趣"


更多架构课程请访问 xdclass.net

 

第1集 Java新特性玩转JDK8之函数式编程 Function

简介:讲解jdk8里面的函数式编程 Function接口的使用

  • Lambda表达式必须先定义接口,创建相关方法之后才可使用,这样做十分不便,其实java8已经内置了许多接口, 例如下面四个功能型接口,所以一般很少会由用户去定义新的函数式接口

  • Java8的最大特性就是函数式接口,所有标注了@FunctionalInterface注解的接口都是函数式接口

Java8 内置的四大核心函数式接口
​
Consumer<T> : 消费型接口:有入参,无返回值
​
    void accept(T t);
​
Supplier<T> : 供给型接口:无入参,有返回值
​
    T get();
​
Function<T, R> : 函数型接口:有入参,有返回值
​
    R apply(T t);
​
Predicate<T> : 断言型接口:有入参,有返回值,返回值类型确定是boolean
​
    boolean test(T t);
​
  • Function

    • 传入一个值经过函数的计算返回另一个值

    • T:入参类型,R:出参类型

      调用方法:R apply(T t)
      
      //@param <T> the type of the input to the function
      //@param <R> the type of the result of the 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);
      ​
      }
      

       

  • 作用:将转换逻辑提取出来,解耦合

  • 不要看过于复杂,就是一个接口,下面是自定义实现

public class FunctionObj implements Function {
    @Override
    public Object apply(Object o) {
        return o+"经过apply处理拼接上了";
    }
}
  • 常规使用

    // 输出入参的10倍
    Function<Integer, Integer> func = p -> p * 100;    
    func.apply(100);
    
    
    

     

 

第2集 Java新特性玩转JDK8之函数式编程 BiFunction

简介:讲解jdk8里面的函数式编程 BiFunction接口的使用

  • BiFunction Function只能接收一个参数,如果要传递两个参数,则用 BiFunction

    @FunctionalInterface
    public interface BiFunction<T, U, R> {
        R apply(T t, U u);
    ​
    }

     

  • 需求: 上两节课,两个数的四则运算

    public static void main(String[] args) {
​
        System.out.println(operator(10,21,(a,b)->a+b));
        System.out.println(operator(10,2,(a,b)->a-b));
        System.out.println(operator(8,4,(a,b)->a*b));
        System.out.println(operator(10,2,(a,b)->a/b));
​
    }
​
    public static Integer operator(Integer a, Integer b, BiFunction<Integer, Integer, Integer> bf) {
​
        return bf.apply(a, b);
    }

第3集 Java新特性玩转JDK8之函数式编程 Consumer

简介:讲解jdk8里面的函数式编程 Consumer接口的使用

  • Consumer 消费型接口:有入参,无返回值

  • 将 T 作为输入,不返回任何内容

    调用方法:void accept(T t);

@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
  • 用途: 因为没有出参,常用于打印、发送短信等消费动作

      public static void main(String[] args) throws Exception {
            Consumer<String> consumer = obj->{
                System.out.println(obj);
                System.out.println("调用短信接口发送短信,或者打印日志");
            };
    ​
    //        sendMsg("8888888",obj->{
    //            System.out.println(obj);
    //            System.out.println("调用短信接口发送短信,或者打印日志");
    //        });
            sendMsg("8888888",consumer);
        }
        public static void sendMsg(String phone,Consumer<String> consumer){
            consumer.accept(phone);
        }

     

  • 典型应用,集合的foreach

    List<String> list  = Arrays.asList("aaa","bbb");
    list.forEach(obj->{ 
    //TODO
    });
    

     

第4集 Java新特性玩转JDK8之函数式编程 Supplier

简介:讲解jdk8里面的函数式编程 Supplier接口的使用

  • Supplier: 供给型接口:无入参,有返回值

  • T:出参类型;没有入参

    调用方法:T get();
    
    @FunctionalInterface
    public interface Supplier<T> {
    T get();
    }

     

  • 用途: 泛型一定和方法的返回值类型是一种类型,如果需要获得一个数据,并且不需要传入参数,可以使用Supplier接口,例如 无参的工厂方法,即工厂设计模式创建对象,简单来说就是 提供者

        public static void main(String[] args) {
            //Student student = new Student();
            Student student = newStudent();
            System.out.println(student.getName());
        }
    ​
        public static Student newStudent(){
            Supplier<Student> supplier = ()-> {
                Student student = new Student();
                student.setName("默认名称");
                return student;
            };
            return supplier.get();
        }
        
        class Student{
            private String name;
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
        }
    

 

第5集 Java新特性玩转JDK8之函数式编程 Predicate

简介:讲解jdk8里面的函数式编程 Predicate接口的使用

  • Predicate: 断言型接口:有入参,有返回值,返回值类型确定是boolean

  • T:入参类型;出参类型是Boolean

    调用方法:boolean test(T t);
    
    @FunctionalInterface
    public interface Predicate<T> {
    boolean test(T t);
    }

     

  • 用途: 接收一个参数,用于判断是否满足一定的条件,过滤数据

    ​
        public static void main(String[] args) {
    ​
            List<String> list = Arrays.asList("awewrwe","vdssdsd","aoooo","psdddsd");
    ​
            List<String> results = filter(list,obj->obj.startsWith("a"));
    ​
            System.out.println(results);
        }
    ​
        public static List<String> filter(List<String> list, Predicate<String> predicate) {
            List<String> results = new ArrayList<>();
            for (String str : list) {
                if (predicate.test(str)) {
                    results.add(str);
                }
            }
    ​
            return results;
        }
    ​
    

     

 

第6集 Java新特性玩转JDK8之方法与构造函数引用

简介:讲解JDK8新特性中 方法引用与构造函数引用

  • 以前方法调用 对象.方法名 或者 类名.方法名

  • jdk1.8提供了另外一种调用方式 ::

    说明:方法引用是一种更简洁易懂的lambda表达式,操作符是双冒号::,用来直接访问类或者实例已经存在的方法或构造方法
    ​
    通过方法引用,可以将方法的引用赋值给一个变量
    ​
    语法:左边是容器(可以是类名,实例名),中间是" :: ",右边是相应的方法名
    ​
    静态方法,则是ClassName::methodName。如 Object ::equals
    实例方法,则是Instance::methodName
    构造函数,则是 类名::new;
    ​
    单个参数
    Function<入参1, 返回类型> func = 方法引用
    应用 func.apply(入参);
    ​
    2个参数
    BiFunction<入参1,入参2, 返回类型> func = 方法引用
    应用 func.apply(入参1,入参2);
    
    
    public class TestJdk8 {
    ​
    public static void main(String[] args) {
        // 使用双冒号::来构造静态函数引用
        Function<String, Integer> fun = Integer::parseInt;
        Integer value = fun.apply("1024");
        System.out.println(value);
    ​
        // 使用双冒号::来构造非静态函数引用
        String content = "欢迎来到小滴课堂学习";
        Function<Integer, String> func = content::substring;
        String result = func.apply(1);
        System.out.println(result);
    ​
        // 构造函数引用,多个参数
        BiFunction<String, Integer, User> biFunction = User::new;
        User user1 = biFunction.apply("小滴课堂", 28);
        System.out.println(user1.toString());
    ​
        //构造函数引用,单个参数
        Function<String, User> function = User::new;
        User user2 = function.apply("小D");
        System.out.println(user2.toString());
    ​
        // 函数引用也是一种函数式接口,可以将函数引用作为方法的参数
        sayHello(String::toUpperCase, "xdclass.net");
    }
    ​
    /**
     *
     * @param func 函数引用
     * @param param 对应的参数
         */
        private static void sayHello(Function<String, String> func, String param) {
            String result = func.apply(param);
            System.out.println(result);
        }
    }
    ​
     class User {
            private String username;
            private Integer age;
    ​
            public User() {
                
            }
            public User(String username) {
                this.username = username;
            }
    ​
            public User(String username, Integer age) {
                this.username = username;
                this.age = age;
            }
        }
    

     

干货文档

                                                        关注公众号发送:“CSDN干货文档”  即可领取

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dev666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值