java8快速入门
2016-06-25 13:11
330 查看
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(e -> System.out.println("Click Detected by Lambda Listner"));
2. Function<S, T> 可用来定义函数变量
使用:
多个function chaining:
Optional (和scala基本一致):
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了。
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(e -> System.out.println("Click Detected by Lambda Listner"));
2. Function<S, T> 可用来定义函数变量
Function<String, Integer> toInteger = Integer::valueOf;
使用:
toInteger.apply("123"); // 123: |
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 |
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了。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树