创建流:
... .stream()
Stream.of(...)
流方法:
处理
filter 过滤、map 映射、sorted 排序、limit 限制、
skip、distinct、match(all..、any..、none..)、find、max、min、reduce、
mapToInt、concat
终结
forEach 遍历、count
例子:
要求:一分钟内完成此题,只能用一行代码实现!
现在有5个用户!筛选:
1、ID 必须是偶数
2、年龄必须大于23岁
3、用户名转为大写字母
4、用户名字母倒着排序
5、只输出一个用户!
UserTestStream u1 = new UserTestStream(1,"a",21); UserTestStream u2 = new UserTestStream(2,"b",22); UserTestStream u3 = new UserTestStream(3,"c",23); UserTestStream u4 = new UserTestStream(4,"d",24); UserTestStream u5 = new UserTestStream(6,"e",25); ListForkJoinlist = Arrays.asList(u1,u2,u3,u4,u5); // 使用stream操作 ()->{} list.stream().filter((u)->{return u.getUserId()%2==0;}) // 过滤出ID为偶数的 .filter(u->u.getAge()>23) // 过滤出年龄大于23岁 .map(u->u.getUserName().toUpperCase()) // 映射 将userName转为大写 .sorted((t1,t2)->t2.compareTo(t1)) // 排序 倒着 .limit(1) // 限制条数 .forEach(System.out::println); // 遍历
ForkJoin 在 JDK 1.7 , 并行执行任务!提高效率。
特点:工作窃取
例子:
求和计算
3000 6000 9000
如何使用 forkjoin
1、 通过forkjoinPool它来执行
ForkJoinPool forkJoinPool = new ForkJoinPool();
2、计算任务
无返回值forkjoinPool.execute(ForkJoinTask> task)
有返回值forkjoinPool.submit(ForkJoinTask
task) 3. 计算类要继承 ForkJoinTask
RecursiveTask
extends ForkJoinTask
public class ForkJoinDemo extends RecursiveTask{ private Long start; private Long end; // private Long temp=10000L; public ForkJoinDemo(Long start, Long end) { super(); this.start = start; this.end = end; } @Override protected Long compute() { // 小于temp=10000条,直接通过for循环 if((end-start) forkJoinTask = new ForkJoinDemo(start, end); ForkJoinTask submit = forkJoinPool.submit(forkJoinTask); // 提交任务 System.out.println(submit.get()); }
普通for循环和stream流方式
// 普通方式
public static void simple(Long start,Long end) {
Long sum = 0L;
for (Long i = start; i <= end; i++) {
sum+=i;
}
System.out.println(sum);
}
// stream方式
public static void testStream(Long start,Long end) {
Long l =LongStream.rangeClosed(start,end).parallel().reduce(0,Long::sum);
System.out.println(l);
}
希望对您有帮助!记得点赞、收藏、关注哦!



