JAVA8新特性

概述

JDK8 新增了⽇期处理、⾃带加解密、Optional特性 掌握JKD8、lambda表达
式和可以实现⾃定义函数式接⼝,如Function、Consumer、Supplier、Predicate。

JDK8之default关键字

在jdk1.8以前接⼝⾥⾯是只能有抽象⽅法,不能有任何⽅法的实现。jdk1.8⾥⾯打破了这个规定,引⼊了新的关键字default,使⽤default修饰⽅法,可以在接⼝⾥⾯定义具体的⽅法实现。

  • 默认⽅法: 接⼝⾥⾯定义⼀个默认⽅法,这个接⼝的实现类实现了这个接⼝之后,不⽤管这个default修饰的⽅法就可以直接调⽤,即接⼝⽅法的默认实现
  • 静态⽅法: 接⼝名.静态⽅法来访问接⼝中的静态⽅法
public interface StudentService {

    /**
     * JAVA8中新增default关键字
     */
    default void test()
    {
        System.out.print("hello world");
    }


    static void test1() {
        System.out.println("这是静态⽅法");
    }
}


JDK8之base64加解密API

Jdk1.8的java.util包中,新增了Base64的类。相比于传统 sun.misc 和 Apache Commons Codec效率较高,不用导包。

public class Base64Demo {

    /**
     * java 8新增 base64编码解码
     * @param args
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        Base64.Encoder encoder = Base64.getEncoder();
        Base64.Decoder decoder = Base64.getDecoder();

        byte[] src = "hello world".getBytes();
        String encodeData = encoder.encodeToString(src);
        System.out.println("编码数据:"+encodeData);

        System.out.println("解码数据:"+ new String(decoder.decode(encodeData),"UTF-8"));
    }
}

JDK8之时间日期处理类

JAVA8新增LocalDate、LocalTime、LocalDateTime日期处理类,LocalDate只精确到天、LocalTime只包含具体时间(时分秒)、LocalDateTime包含日期和时间。新增DateTimeFormatter(线程安全)和Duration对时间的处理变得极为方便,具体使用如下。

class LocalDateDemo {

    public static void main(String[] args) throws InterruptedException {

        /**
         * LocalDate不包含具体时间(小时、分、秒),只有日期
         */
        LocalDate localDate = LocalDate.now();

        System.out.println("当前时间:"+ localDate);
        System.out.println("当前月份"+localDate.getMonthValue());

        //增加
        LocalDate newLocalDate = localDate.plusYears(2);
        System.out.println("增加的时间"+newLocalDate);

        //减小
        LocalDate minLocalDate = localDate.minusYears(66);
        System.out.println("减小的时间"+minLocalDate);

        //修改月份
        LocalDate localDate1 =localDate.withMonth(5);
        System.out.println(localDate1);

        LocalDateTime localDateTime = LocalDateTime.now();
        Thread.sleep(1111);
        System.out.println(localDateTime.isAfter(LocalDateTime.now()));


        //DateTimeFormatter线程安全
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String ldtStr = dtf.format(ldt);
        System.out.println(ldtStr);

        //时间比较
        LocalDateTime today = LocalDateTime.now();
        System.out.println(today);
        LocalDateTime changeDate = LocalDateTime.of(2020,10,1,10,40,30);
        System.out.println(changeDate);
        Duration duration = Duration.between( today,changeDate);//第⼆个参数减第⼀个参数

        System.out.println(duration.toDays());//两个时间差的天数
        System.out.println(duration.toHours());//两个时间差的⼩时数
        System.out.println(duration.toMinutes());//两个时间差的分钟数
        System.out.println(duration.toMillis());//两个时间差的毫秒数
        System.out.println(duration.toNanos());//两个时间差的纳秒数


    }
}

JDK8之Lambda表达式

在JDK8之前,Java是不⽀持函数式编程的,所谓的函数编程,即可理解是将⼀个函数(也称为“⾏为”)作为⼀个参数进⾏传递, ⾯向对象编程是对数据的抽象,⽽函数式编程则是对⾏为的抽象(将⾏为作为⼀个参数进⾏传递)。
lambda表达式 使⽤场景(前提):⼀个接⼝中只包含⼀个⽅法,则可以使⽤Lambda表达式,这样的接⼝称之为“函数接⼝” 语法: (params) -> expression。

public class LamadaDemo {

    public static void main(String[] args) {

        /**
         * JDK8之前创建线程
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        });

        //JDK8
        new Thread(()->System.out.println("hello world"));


        //JDK8之前排序
        List<String> list = Arrays.asList("aaa","ggg","ffff","ccc");
        Collections.sort(list, new Comparator<String>() {
                    @Override
                    public int compare(String a, String b) {
                        return b.compareTo(a);
                    }
                }
        );
        for (String string : list) {
            System.out.println(string);
        }

        //JDK8排序
        Collections.sort(list, (a,b)->b.compareTo(a)
        );
        for (String string : list) {
            System.out.println(string);
        }

        
    }
}

自定义函数编程
定义一个函数式接口:

//声明这是一个函数式接口
@FunctionalInterface
public interface MyLamada<R,T> {
    R operator(T t1,T t2);
}

测试:

public class MyLamadaTest {

    public static void main(String[] args) throws Exception {
        System.out.println(operator(20, 5, (Integer x, Integer y) -> {
            return x * y;
        }));
        System.out.println(operator(20, 5, (x, y) -> x + y));
        System.out.println(operator(20, 5, (x, y) -> x - y));
        System.out.println(operator(20, 5, (x, y) -> x / y));
    }
    public static Integer operator(Integer x, Integer y,
                                   MyLamada<Integer, Integer> of) {
        return of.operator(x, y);
    }
}

JDK8 函数式编程

Lambda表达式必须先定义接⼝,创建相关⽅法之后才可使⽤,这样做⼗分不便,其实java8已经内置了许多接⼝, 例如下⾯四个功能型接⼝,所以⼀般很少会由⽤户去定义新的函数式接⼝。Java8 内置的四⼤核⼼函数式接⼝:

  1. Consumer : 消费型接⼝:有⼊参,⽆返回值
  2. Supplier : 供给型接⼝:⽆⼊参,有返回值
  3. Function<T, R> : 函数型接⼝:有⼊参,有返回值
  4. Predicate : 断⾔型接⼝:有⼊参,有返回值,返回值类型确定是boolean
public class FunctionDemo {

    public static void main(String[] args) {
        //声明function函数
        Function<Integer,Integer> function = p->p*10;
        System.out.println(function.apply(99));

        //自定义function函数,只能穿一个参数
        MyFunction<String,String> myFunction = new MyFunction<>();
        System.out.println(myFunction.apply("xw study"));

        //BiFunction支持传两个参数
        BiFunction<String,String,String> biFunction = (a,b)->a+b;
        System.out.println(biFunction.apply("a","b"));


    }
}


/**
 * @author by xw
 * @Description predicate有入参,有返回值,返回类型是boolean类型
 */
public class PredicateDemo {
    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;
    }
}




/**
 * @author by xw
 * @Description supplier只有返回值,没有入参
 */
public class SupplierDemo {
    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();
    }

    static class Student{
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
}

public class ConsumerDemo {

    public static void main(String[] args) throws Exception {
        Consumer<String> consumer = obj->{
            System.out.println(obj);
            System.out.println("调⽤短信接⼝发送短信,或者打印⽇志");
        };

        sendMsg("8888888",consumer);
    }
    public static void sendMsg(String phone, Consumer<String> consumer){
        consumer.accept(phone);
    }
}

未完待续。。。。。
项目地址:项目地址

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值