Java8函数式编程对提高代码简洁性和操作方便性是有很大作用的,废话少说,贴一个demo,具体其他功能举一反三吧!
package com.app.demo.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Run {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
Integer num = (int) (100 * Math.random());
nums.add(num);
System.out.println(num.intValue());
}
// predicate语义
Predicate<Integer> p1 = x -> x.intValue() > 3 && x.intValue() < 19;
Predicate<Integer> p2 = x -> x.intValue() > 30 && x.intValue() < 80;
// 流式操作
List<Integer> res = nums.stream().filter(p1.and(p2)).collect(Collectors.toList());
// 排序,Comparator
Collections.sort(res, Comparator.comparing(Integer::intValue));
// Optional
List<Integer> value = Optional.ofNullable(res).map((param) -> {
return param.stream().map(x -> x / 3).collect(Collectors.toList());
}).orElseThrow(IllegalArgumentException::new);
System.out.println(value.size());
}
}