java8快速入门

java8也推出很久了,我总是后知后觉,最近要用看了看,发现特性高度重合scala, 熟悉scala的应该很容易上手。读了个介绍,稍微整理了下:


1. lambda expression could be used to replace inner anonymous class, if the inner anonymous class only contains one method to override. To enforce this, add annotation @FunctionalInterface
Sample:

  
JButton testButton  =  new  JButton ( " Test   Button " );
// 1. regular ways to do
testButton. addActionListener ( new  ActionListener ( ) {
   @ Override  public  void  actionPerformed (ActionEvent ae ) {
    System.out. println ( " Click   Detected   by   Anon   Class " );
  }
} );
// 2. use LAMBDA expression
testButton. addActionListener (- > System.out. println ( " Click   Detected   by   Lambda   Listner " ) );

2. Function<S, T> 可用来定义函数变量
Function<String, Integer> toInteger = Integer::valueOf;
使用:
toInteger.apply("123");     // 123:
多个function chaining:
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;

times2.compose(squared).apply(4);  
// Returns 32, do squared first, then times2

times2.andThen(squared).apply(4);  
// Returns 64, do time2 first, then squared



  1. Optional (和scala基本一致):
Optional<String> optional = Optional.of("bam");

optional.isPresent();           // true
optional.get();                 // "bam"
optional.orElse("fallback");    // "bam"

optional.ifPresent((s) -> System.out.println(s.charAt(0)));     // "b"
4. stream
     .stream() 将list类的对象变成stream,然后连接操作,操作分两类,一类输出还是一个流(map),一类会进行归并(reduce),类似mapreduce:
map类: filter, sorted, map, 
reduce类:match(包括anyMatch, allMatch, nonMatch,predicate为参数,返回boolean),count,reduce(某操作为参数,返回Optional)

  parellelStream()并行操作流操作 

其他feature可以边看边学。感觉java8也基本盖上了scala的棺材盖了,可以理解为什么lnkd也要弃用scala了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值