Java8新特性实践

1、Lambda表达式/闭包。

参考 http://www.runoob.com/java/java8-lambda-expressions.html

/**
 * <pre>
 *     1, Lambda表达式,也可称为闭包。是对《接口匿名实现类》的一种简化
 *     2, Lambda 允许把函数作为一个方法的参数,《接口的匿名实现类》作为引用传递
 *     3, Lambda 操作符"->", 左侧师入参,右侧是表达式功能
 * </pre>
 */
public class LambdaTester {
   public static void main(String args[]){
      LambdaTester tester = new LambdaTester();
        
      // 类型声明
      MathOperation addition = (int a, int b) -> a + b;
        
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
        
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> { int c = b + 1; return a * c; };


      System.out.println("============《接口的匿名实现类》直接调用==========");
      System.out.println("10 + 5 = " + addition.operation(10, 5));
      System.out.println("============《接口的匿名实现类》作为引用传递==========");
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));

      // 其他方法
      HelloService helloService = name -> System.out.println("Hello " + name);
      System.out.println("============《接口的匿名实现类》直接调用==========");
      helloService.hello("tomcat");
   }
    
   interface MathOperation {
      int operation(int a, int b);
   }
    
   interface HelloService {
      void hello(String name);
   }
    
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

2、函数式接口

接口中只包含一个抽象方法的接口,称为函数式接口。
可以使用@FunctionalInterface注解修饰该接口。

//内置的4种函数式接口
Supplier<T>{//供给型
	T get();
}
Consumer<T>{ //消费型
	void accept(T t);
}
Predicate<T> {//谓语断言型, //函数型返回为boolean时就是断言型。
	boolean test(T t);
}
Function<T, R> {//函数型
	R apply(T t);
}

3. Stream API

Map<String, String> map1 = ids.stream().collect(Collectors.toMap(e -> e, e -> "123"));
Map<String, String> map2 = users.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getName()));

4.Optional——容器类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值