Java 8 新特性 简单记录

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 来标明是函数式接口

@FunctionalInterface
public 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/ 很详细!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值