Java 8 新特性 简单记录

来源:互联网 发布:软件开发编程培训 编辑:程序博客网 时间:2024/05/29 18:24

Java 8 新特性

一.接口的默认方法

举个例子

public interface DefultInterface {    int add(int x , int y);    default int getValue(int x){        return x;    };}    @Override    public int add(int x, int y) {        return getValue(x)+y;    }    public static void main(String[] args) {        DefaultInterfaceTest d = new DefaultInterfaceTest();        System.out.println(d.add(3, 4));    }

在interface 中 Default 方法可以被直接调用,而且具有方法体!

二.Lambda 表达式

λ表达式主要用于替换以前广泛使用的内部匿名类,各种回调,比如事件响应器、传入Thread类的Runnable等

public static void main(String[] args) {    List<Integer> list = new ArrayList<>(Arrays.asList(1,2,5,3,7));    Collections.sort(list,(x,y)->Integer.compare(x, y));    System.out.print(list);}}

三.函数式接口

使用FunctionalInterface 来标明是函数式接口

@FunctionalInterfacepublic interface FunInterface {    int getValue(int x);}

四.四大函数接口

java提供四大函数式接口

    函数            主要方法 Consumer<T>     void accept(T t)  Supplier<T>     T get(); Function<T, R>  R apply(T t); Predicate<T>    boolean test(T t);

四大函数式接口简单示例

@Test    public void test1(){        boolean b = TrueOrFalse("helloWord", x->x.equals("helloWord"));        System.out.println(b);    }    public boolean TrueOrFalse(String s1,Predicate<String> predicate){    //参与判断 返回boolean        return predicate.test(s1);    }    @Test    public void test2(){        ConsumerTest("helloWord",(x)->System.out.println(x.substring(2, 4)));    }    public void ConsumerTest(String s1,Consumer<String> consumer){    // 消费者‘只管消费’--有参数但是没有返回值        consumer.accept(s1);    }    @Test    public void test3(){        int x =  SupplierTest(()->Integer.compare(2, 5));        System.out.println(x);    }    public int SupplierTest(Supplier<Integer> supplier){//      供给者’只提供‘ --没有参数但是有返回值        return supplier.get();    }    @Test    public void test4(){      String str =  word("helloword",(p)-> p.toUpperCase());        System.out.println(str);    }    public String word (String name,Function<String,String> people){    //有参数Function<R,T> 其中R代表参数 T代表返回值       return people.apply(name);    }

五.Stream API

参考 https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/ 很详细!!!

原创粉丝点击