jdk8新特性

接口可以定义默认方法和静态方法

为什么要增加一个默认接口呢?

为了兼容旧版本,因为java8在之前的接口中增加了方法,比如在Collection中增加了方法,那么所有容器都得增加方法的实现,但是增加了默认的实现方法,就可以减少改动。

package com.jdk8.newpat;

public interface InterfacePat{
	void method1(String s);
	/*
	 * 接口可以定义默认方法
	 */
	default void defaultMethod() {
		System.out.println("i am interface's default method");
	}
	/**
	 * 接口可以定义静态方法
	 */
	static void staticMethod() {
		System.out.println("i am interface's static method");
	}
}

 Lambda表达式
 

package com.jdk8.newpat;

public class TestMain {
	public static void main(String[] args) {
		LambdaTest lambdaTest = ()->System.out.println("i am method");
		lambdaTest.method();
	}
}
interface LambdaTest {
	void method();
}


输出
i am method

 

forEach使用

package com.jdk8.newpat;

import java.util.ArrayList;
import java.util.List;

public class UserForEach {
	public static void main(String[] args) {
		List list =new ArrayList<>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.forEach((one)-> System.out.println(one));
	}
}


输出
1
2
3

Stream,是对集合对象功能的增强,原理利用管道封装操作,减少中间数据的生产和迭代次数。

package com.jdk8.newpat;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class UserStream {
	private static int userStreamMax(List list) {
		if(list == null) {
			return -1;
		}
		return list.stream().max((a, b) -> {
            if (a > b) {
                return 1;
            } else return -1;
        }).get();
	}
	private static int userStreamFilter(List list) {
		if(list == null) {
			return -1;
		}
		list.stream().filter(integer -> integer<3).forEach(System.out::println);;
		return 0;
	}
	private static void userStreamSoted(List list) {
		if(list == null) {
			return;
		}
		list.stream().sorted((a,b)->a-b).forEach(System.out::print);
	}
	public static void main(String[] args) {
		List list = Arrays.asList(1, 2, 3, 8, 5, 6);
		System.out.println("max is :"+userStreamMax(list));
		System.out.println("user stream filter");
		userStreamFilter(list);
		System.out.println("user stream soted ");
		userStreamSoted(list);
		
	}
}

新时间API使用 

 private static void userTime(){
        //localDate
        LocalDate localDate = LocalDate.of(2020,8,2);
        System.out.println(localDate.getMonth());
        //LocalTime
        LocalTime localTime = LocalTime.of(21, 48, 0);

        //LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.of(2020, 8, 2,21,50,0);
        LocalDateTime localDateTime1 = LocalDateTime.of(localDate, localTime);
        LocalDateTime localDateTime2 = LocalDateTime.now();

        Instant instant2 = localDateTime2.atZone(ZoneId.systemDefault()).toInstant();
        System.out.println("milli:"+ instant2.toEpochMilli());
        //Instant
        Instant instant = Instant.now();
        System.out.println(instant);
    }

 

jdk8新特性_第1张图片

你可能感兴趣的:(java)