嘉兴 网站制作,wordpress php 模板,北京网上网页设计培训,盐城市建设工程网站#xff08;1#xff09;Stream
Stream#xff08;流#xff09;是一个来自数据源的元素队列并支持聚合操作。 forEach方法用来迭代流中的每个数据#xff0c;没有返回值。map方法用于映射每个元素到对应的结果#xff0c;有返回值#xff0c;返回的是一个新流#xf…1Stream
Stream流是一个来自数据源的元素队列并支持聚合操作。 forEach方法用来迭代流中的每个数据没有返回值。map方法用于映射每个元素到对应的结果有返回值返回的是一个新流可以对这个流进一步操作。 filter方法用于通过设置的条件过滤出元素。limit返回前n个元素。skip则是返回除前n个元素的元素。distinct方法用于去重。 sorted方法用于对流进行排序例如sorted()用于升序sorted(Comparator.reverseOrder())用于降序。 max用于获取最大值。min用于获取最小值。count用于计算元素数量。sum用于求和。 anyMatch满足一个条件则返回true。allMatch满足所有条件则返回true。noneMatch不满足所有条件则返回true。findFirst返回第一个元素。findAny返回任意一个元素。 collect收集流。Collectors类实现了很多归约操作例如toList、toMap、toSet、counting、summingInt、averagingInt、maxBy、minBy、joining、groupingBy等等。 reduce聚合将流中全部的数据聚合成一个值。
2测试
User tom new User(1, tom, 2, new Date());
User jerry new User(3, jerry, 1, new Date());
User diana new User(2, diana, 3, new Date());
ListUser userList Arrays.asList(tom, jerry, diana);
log.info(list:{}, userList);
userList.stream().forEach(u - {if (u.getAge() 1) {log.info({}, u);}
});
ListInteger list userList.stream().map(u - u.getAge() 1).limit(10).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
log.info(list:{}, list);
MapInteger, Object map userList.stream().collect(Collectors.toMap(User::getId, User::getName));
log.info(map:{}, map);
boolean flag userList.stream().anyMatch(u - u.getAge() 5);
log.info(flag:{}, flag);
User any userList.stream().findAny().get();
log.info(any:{}, any);
User max userList.stream().max((u1, u2) - u1.getAge() - u2.getAge()).get();
log.info(max:{}, max);
Integer sum userList.stream().map(u - u.getAge()).reduce(0, (a1, a2) - {return a1 a2;
}).intValue();
log.info(sum:{}, sum);
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - list:[User(id1, nametom, age2, birthFri Jan 26 14:45:26 CST 2024), User(id3, namejerry, age1, birthFri Jan 26 14:45:26 CST 2024), User(id2, namediana, age3, birthFri Jan 26 14:45:26 CST 2024)]
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - User(id1, nametom, age2, birthFri Jan 26 14:45:26 CST 2024)
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - User(id2, namediana, age3, birthFri Jan 26 14:45:26 CST 2024)
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - list:[4, 3, 2]
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - map:{1tom, 2diana, 3jerry}
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - flag:false
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - any:User(id1, nametom, age2, birthFri Jan 26 14:45:26 CST 2024)
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - max:User(id2, namediana, age3, birthFri Jan 26 14:45:26 CST 2024)
2024-01-26 14:45:26 [http-nio-8080-exec-4] INFO cn.hwd.controller.TestController - sum:6