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<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 |
- 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了。