jdk1.8 Java8新特性使用汇总

1. 接口和日期

default关键字

在jdk1.8以前接口里里面是只能有抽象方法,不不能有任何⽅方法的实现的。jdk1.8里面打破了了这个规定,引入了了新的关键字default,使用default修饰方法,可以在接口里里面
定义具体的方法实现

默认方法: 接口里里面定义一个默认方法,这个接⼝口的实现类实现了了这个接口之后,不用管这个
default修饰的方法就可以直接调用,即接口方法的默认实现

public interface Animal {
	void run();
	void eat();
	default void breath(){
		System.out.println("使⽤用氧⽓气呼吸");
	}
}

静态方法: 接口名.静态方法来访问接口中的静态方法

public interface Animal {
	void run();
	void eat();
	default void breath(){
		System.out.println("使⽤用氧⽓气呼吸");
	}
}
public interface Animal {
	void run();
	void eat();
	default void breath(){
		System.out.println("使⽤用氧⽓气呼吸");
	}
	static void test(){
		System.out.println("这是静态⽅方法")
	};
}

base64加解密API

什什么是Base64编码 Base64是⽹网络上最常⻅见的⽤用于传输8Bit字节码的编码⽅方式之⼀一,Base64就是
⼀一种基于64个可打印字符来表示⼆二进制数据的⽅方法 基于64个字符A-Z,a-z,0-9,+,/的编码⽅方式,
是⼀一种能将任意⼆二进制数据⽤用64种字元组合成字符串串的⽅方法,⽽而这个⼆二进制数据和字符串串资料料之
间是可以互相转换的,在实际应⽤用上,Base64除了了能将⼆二进制数据可视化之外,也常⽤用来表示字串加密过后的内容

推荐⼀一个⽂文章:https://blog.csdn.net/wo541075754/article/details/81734770
jdk1.8之后怎么玩
Jdk1.8的java.util包中,新增了了Base64的类
好处:不用引包,编解码销量量远⼤大于 sun.misc 和 Apache Commons Codec

Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
String text = "XXXXXXXX";
byte[] textByte = text.getBytes("UTF-8");
//编码
String encodedText = encoder.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decode(encodedText), "UTF-
8"));

时间日期处理理类

  1. 时间处理理再熟悉不不过,SimpleDateFormat,Calendar等类 旧版缺点: java.util.Date 是非线程安全的, API设计比较差,日期/时间对象比较,加减麻烦
  2. Java 8通过发布新的Date-Time API (JSR 310)来进一步加强对日期与时间的处理理
    - 新增了了很多常⻅见的api,如⽇日期/时间的⽐比较,加减,格式化等
    - 包所在位置 java.time
    - 核心类
		LocalDate:不不包含具体时间的⽇日期。
  		LocalTime:不不含⽇日期的时间。
  		LocalDateTime:包含了了日期及时间。
		- LocalDate 常用API
LocalDate today = LocalDate.now();
System.out.println("今天⽇日期:" + today);
//获取年年,⽉月,⽇日,周⼏几
System.out.println("现在是哪年年:"+today.getYear());
System.out.println("现在是哪⽉月:"+today.getMonth());
System.out.println("现在是哪⽉月(数字):"+today.getMonthValue());
System.out.println("现在是⼏几号:"+today.getDayOfMonth());
System.out.println("现在是周⼏几:"+today.getDayOfWeek());

LocalDate changeDate = today.plusYears(1);
System.out.println("加后是哪年年:"+changeDate.getYear());
System.out.println("旧的是哪年年:"+today.getYear());
//⽇日期⽐比较
System.out.println("isAfter: "+changeDate.isAfter(today));
//getYear() int 获取当前⽇日期的年年份
//getMonth() Month 获取当前⽇日期的⽉月份对象
//getMonthValue() int 获取当前⽇日期是第⼏几⽉月
//getDayOfWeek() DayOfWeek 表示该对象表示的⽇日期是星期⼏几
//getDayOfMonth() int 表示该对象表示的⽇日期是这个⽉月第⼏几天
//getDayOfYear() int 表示该对象表示的⽇日期是今年年第⼏几天
//withYear(int year) LocalDate 修改当前对象的年年份
//withMonth(int month) LocalDate 修改当前对象的⽉月份
//withDayOfMonth(int dayOfMonth) LocalDate 修改当前对象在当⽉月的⽇日//plusYears(long yearsToAdd) LocalDate 当前对象增加指定的年年份数
//plusMonths(long monthsToAdd) LocalDate 当前对象增加指定的⽉月份数
//plusWeeks(long weeksToAdd) LocalDate 当前对象增加指定的周数
//plusDays(long daysToAdd) LocalDate 当前对象增加指定的天数
//minusYears(long yearsToSubtract) LocalDate 当前对象减去指定的年年//minusMonths(long monthsToSubtract) LocalDate 当前对象减去注定的
⽉月数
//minusWeeks(long weeksToSubtract) LocalDate 当前对象减去指定的周//minusDays(long daysToSubtract) LocalDate 当前对象减去指定的天数
//compareTo(ChronoLocalDate other) int ⽐比较当前对象和other对象在时
间上的⼤大⼩小,返回值如果为正,则当前对象时间较晚,
//isBefore(ChronoLocalDate other) boolean ⽐比较当前对象⽇日期是否在
other对象⽇日期之前
//isAfter(ChronoLocalDate other) boolean ⽐比较当前对象⽇日期是否在
other对象⽇日期之后
//isEqual(ChronoLocalDate other) boolean ⽐比较两个⽇日期对象是否相等
  1. 日期时间格式化
    • JDK8之前:SimpleDateFormat来进行格式化,但SimpleDateFormat并不不是线程安全的
    • JDK8之后:引入线程安全的日期与时间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 ldt = LocalDateTime.of(2020, 11, 11, 8, 20, 30);
System.out.println(ldt);
- 计算日期时间差 java.time.Duration
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());//两个时间差的纳秒数

2. Lambda表达式 函数式编程 集合框架 收集器器和集合统计

public class Main {
    public static void main(String[] args) {
        // default interface
        Animal dog = new Dog();
        dog.run();
        dog.breath();
        Animal.speak();

        //Date and Time
        LocalDate today = LocalDate.now();
        System.out.println(today);
        System.out.println(today.getMonth());
        System.out.println(today.getDayOfMonth());
        System.out.println(today.plusDays(1).isAfter(today.minusDays(1)));

        LocalDateTime todayTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
        System.out.println(dtf.format(todayTime));

        LocalDateTime changedTime = LocalDateTime.of(2099, 1, 1, 1, 1, 2);
        System.out.println(changedTime);
        System.out.println(Duration.between(todayTime, changedTime).toDays());

        //Optional
        Animal animal = null;
        Animal a = Optional.ofNullable(animal).orElse(new Dog());
        a.run();
        Optional opt = Optional.ofNullable(new Dog());
        System.out.println(opt.isPresent());

        //Function
        test("123", new FunctionObj());
        Function<Integer, Integer> func = p -> p * 100;
        System.out.println(func.apply(2));
        BiFunction<Integer, Integer, Integer> bf = (p1, p2) -> p1 * p2;
        System.out.println(bf.apply(3, 2));

        //Consumer
        Consumer con = p -> System.out.println(p);
        Consumer then = p -> System.out.println("after: " + p);
        con.accept("accept test");
        con.andThen(then).accept("123");
        List<String> list = Arrays.asList("abc", "afg", "qwe");
        list.forEach(l -> System.out.println(l));

        //Supplier
        Supplier<Dog> supplier = () -> { Dog d = new Dog(); return d; };
        supplier.get().run();

        //Predicate
        System.out.println(filter(list, obj -> obj.startsWith("a")));


        //总价 35
        List<VideoOrder> videoOrders1 = Arrays.asList(
                new VideoOrder("20190242812", "springboot教程", 3),
                new VideoOrder("20194350812", "微服务SpringCloud", 5),
                new VideoOrder("20190814232", "Redis教程", 9),
                new VideoOrder("20190523812", "⽹网⻚页开发教程", 9),
                new VideoOrder("201932324", "百万并发实战Netty", 9));
        //总价 54
        List<VideoOrder> videoOrders2 = Arrays.asList(
                new VideoOrder("2019024285312", "springboot教程", 3),
                new VideoOrder("2019081453232", "Redis教程", 9),
                new VideoOrder("20190522338312", "⽹网⻚页开发教程", 9),
                new VideoOrder("2019435230812", "Jmeter压⼒力力测试", 5),
                new VideoOrder("2019323542411", "Git+Jenkins持续集成", 7),
                new VideoOrder("2019323542424", "Idea全套教程", 21));
        List<VideoOrder> xx = videoOrders1.stream().filter(obj -> {
            return videoOrders2.stream().anyMatch(o2 -> o2.getTitle().equals(obj.getTitle()));
        }).collect(Collectors.toList());

        xx.forEach(obj -> System.out.println(obj.getTitle()));
    }

    static void test(String input, Function f) {
        System.out.println(f.apply(input));
    }

    static List<String> filter(List<String> input, Predicate<String> predicate){
        List<String> startWithA = new ArrayList<String>();
        for(String i : input) {
            if(predicate.test(i)) {
                startWithA.add(i);
            }
        }
        return startWithA;
    }
}
发布了24 篇原创文章 · 获赞 15 · 访问量 1144

猜你喜欢

转载自blog.csdn.net/shenhuxi10000/article/details/104810975