2. Lambda表达式
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("button clicked");
}
});
变成—–>
button.addActionListener(event -> System.out.println("button clicked"));
2.1. 各种类型的lambda表达式
Runnable anArgments = () -> System.out.println("Hello World");
ActionListener oneArgment = event -> System.out.println("button clicked");
Runnable anArgments = () -> {
System.out.println("Hello World");
System.out.println("Hello World");
};
BinaryOperator<Long> add = (x, y) -> x + y;
BinaryOperator<Long> add = (Long x, Long y) -> x + y;
Lamba表达式中使用方法中的变量时,变量其实相当于添加了final属性
2.2. 函数接口
函数接口是只有一个抽象方法的接口,用作Lambda表达式的类型
3. 流
int count = 0;
for (Artist artist : allArtists) {
if (artist.isFrom("London")) {
count++;
}
}
—>转化为
long count = allArtists.stream()
.filter(artist -> artist.isFrom("London"))
.count();
3.1 常用流操作
//collect(toList())
List<String> collected = Stream.of("a","b","c").collect(Collectors.toList());
//map
List<String> collected = Stream.of("a","b","hello").map(string -> string.toUpperCase()).collect(toList());
//filter
List<String> beginningWithNumbers = Stream.of("a","1abc","abc1").filter(value -> isDigit(value.charAt(0))).collect(toList());
//flatMap
List<Integer> together = Stream.of(asList(1, 2), asList(3, 4)).flatMap(numbers -> numbers.stream()).collect(toList());
//max&min
Track shortestTrack = tracks.stream().min(Comparator.comparing(track -> track.getLength())).get()
//reduce求和
int count = Stream.of(1, 2, 3).reduct(0, (acc, element) -> acc + element);