鞍山晟宇网站建设,做影视后期应该关注哪些网站,百度营销登录入口,网站建设与管理以后工作方向#x1f473;我亲爱的各位大佬们好#x1f618;#x1f618;#x1f618; ♨️本篇文章记录的为 Stream流、函数式编程 相关内容#xff0c;适合在学Java的小白,帮助新手快速上手,也适合复习中#xff0c;面试中的大佬#x1f649;#x1f649;#x1f649;。 ♨️如果… 我亲爱的各位大佬们好 ♨️本篇文章记录的为 Stream流、函数式编程 相关内容适合在学Java的小白,帮助新手快速上手,也适合复习中面试中的大佬。 ♨️如果文章有什么需要改进的地方还请大佬不吝赐教❤️ 个人主页 : 阿千弟 上期内容 : 都2023年了,如果不会Lambda表达式、函数式编程你确定能看懂公司代码 都2023年了,如果你不会Stream流、函数式编程你确定能看懂同事写的代码 那么建议来了解一下Stream流, 因为它使用简单,易操作,易上手而代码简洁开发快速,一看就令人很爽 . 其实Stream流式编程表达式接近自然语言易于理解 , 集万千优点与一身, 语法优美.下面来简单认识一下今天的主角Stream流吧
文章目录介绍环境准备常用操作创建流中间操作filtermapdistinctsortedlimitskip(硬核分页)flatMap终结操作forEachcountmaxmincollect查找与匹配anyMatchallMatchnoneMatchfindAnyfindFirstreduce归并介绍
Java8的Stream使用的是函数式编程模式但是此流非彼流, 不像我们以前认识到的I/O流等, 既不是字节流也不是字符流. 如同它的名字一样Stream可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。
环境准备
引入lombok依赖, 可以方便我们后期对实体类的操作 dependenciesdependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion1.18.12/version/dependency/dependenciesAuthor 实体类和Book实体类
Author和Book之间是一对多关系, 每个Author包含多个Book
Data
NoArgsConstructor
AllArgsConstructor
EqualsAndHashCode//用于后期的去重使用
public class Author {//idprivate Long id;//姓名private String name;//年龄private Integer age;//简介private String intro;//作品private ListBook books;
}Data
AllArgsConstructor
NoArgsConstructor
EqualsAndHashCode//用于后期的去重使用
public class Book {//idprivate Long id;//书名private String name;//分类private String category;//评分private Integer score;//简介private String intro;}数据初始化
private static ListAuthor getAuthors() {//数据初始化Author author new Author(1L,蒙多,33,一个从菜刀中明悟哲理的祖安人,null);Author author2 new Author(2L,亚拉索,15,狂风也追逐不上他的思考速度,null);Author author3 new Author(3L,易,14,是这个世界在限制他的思维,null);Author author4 new Author(3L,易,14,是这个世界在限制他的思维,null);//书籍列表ListBook books1 new ArrayList();ListBook books2 new ArrayList();ListBook books3 new ArrayList();books1.add(new Book(1L,刀的两侧是光明与黑暗,哲学,爱情,88,用一把刀划分了爱恨));books1.add(new Book(2L,一个人不能死在同一把刀下,个人成长,爱情,99,讲述如何从失败中明悟真理));books2.add(new Book(3L,那风吹不到的地方,哲学,85,带你用思维去领略世界的尽头));books2.add(new Book(3L,那风吹不到的地方,哲学,85,带你用思维去领略世界的尽头));books2.add(new Book(4L,吹或不吹,爱情,个人传记,56,一个哲学家的恋爱观注定很难把他所在的时代理解));books3.add(new Book(5L,你的剑就是我的剑,爱情,56,无法想象一个武者能对他的伴侣这么的宽容));books3.add(new Book(6L,风与剑,个人传记,100,两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢));books3.add(new Book(6L,风与剑,个人传记,100,两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢));author.setBooks(books1);author2.setBooks(books2);author3.setBooks(books3);author4.setBooks(books3);ListAuthor authorList new ArrayList(Arrays.asList(author,author2,author3,author4));return authorList;}常用操作
创建流
单列集合 集合对象.stream() ListAuthor authors getAuthors();StreamAuthor stream authors.stream();数组Arrays.stream(数组) 或者使用Stream.of来创建 Integer[] arr {1,2,3,4,5};StreamInteger stream Arrays.stream(arr);StreamInteger stream2 Stream.of(arr);双列集合转换成单列集合后再创建 MapString,Integer map new HashMap();map.put(天邪龙王,19);map.put(天启帝君,17);map.put(圣灵谱尼,16);StreamMap.EntryString, Integer stream map.entrySet().stream();中间操作
filter 作用 : 可以对流中的元素进行条件过滤符合过滤条件的才能继续留在流中。 //打印所有年龄小于18的作家的名字并且要注意去重ListAuthor authors getAuthors();authors.stream().distinct().filter(new PredicateAuthor() {Overridepublic boolean test(Author author) {return author.getAge() 18;}})//筛选年龄小于18的.forEach(new ConsumerAuthor() {Overridepublic void accept(Author author) {System.out.println(author.getName());}});//遍历打印名字其中authors.stream()操作把authors集合转化为stream流对象, .distinct()的作用是去除重复, .filter()中通过使用匿名内部类重写Predicate接口中的test()方法对条件进行过滤, .forEach()是终结操作(下面会进行解释说明)
有了这几个条件, 我们可以使用lambda表达式的方法将其进一步简化一下
对lambda表达式不太了解的小老弟小老妹儿可以点击这儿了
ListAuthor authors getAuthors();authors.stream().filter(author - author.getName().length()1).forEach(author - System.out.println(author.getName()));map 作用 : 可以把对流中的元素进行计算或转换。 官方文档的解释是 :
返回由将给定函数应用于此流元素的结果组成的流。 这是一个中间操作。 参数mapper–应用于每个元素的无干扰无状态函数 类型参数 –新流的元素类型 返回新流
此map非彼map 这里的map方法不是转换为Mapk,v对象的意思谨记谨记。 map本意就是映射只不过java中map更多指代集合说的是一个键根据映射可以找到一个值这里map只是又回归了本来的含义。
例如
打印所有作家的姓名 authors.stream().map(new FunctionAuthor, String() {Overridepublic String apply(Author author) {return author.getName();}}).forEach(new ConsumerString() {Overridepublic void accept(String name) {System.out.println(name);}});在更多的时候我们见到的都是lambda表达式写法, //获取所有作者的名字ListAuthor authors getAuthors();authors.stream().map(author - author.getName()).forEach(name-System.out.println(name));//获取所有作者的年龄并加上10authors.stream().map(author - author.getAge()).map(age-age10).forEach(age- System.out.println(age));对于复杂的中间操作, 相同的方法可以使用多次
distinct 作用 : 可以去除流中的重复元素。 例如
打印所有作家的姓名并且要求其中不能有重复元素。 ListAuthor authors getAuthors();authors.stream().distinct().forEach(author - System.out.println(author.getName()));执行流程 注意distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。 Object的equals方法是直接使用来进行比较的, 也就是说如果两个对象的地址值相同则会判定是同一个对象, 但是在实际的生产过程中并不是只判定地址是否相同, 如果两个对象的所有属性都相同我们就也可以判定是同一个对象, 所以我们要重写equals方法和hashCode方法.
sorted 作用 : 可以对流中的元素进行排序。 例如
对流中的元素按照年龄进行降序排序并且要求不能有重复的元素。 ListAuthor authors getAuthors();
//对流中的元素按照年龄进行降序排序并且要求不能有重复的元素。authors.stream().distinct().sorted().forEach(author - System.out.println(author.getAge()));sorted()使用:
实现compare接口传一个匿名对象 目的实现比较逻辑 ListAuthor authors getAuthors();
// 对流中的元素按照年龄进行降序排序并且要求不能有重复的元素。authors.stream().distinct().sorted((o1, o2) - o2.getAge()-o1.getAge()).forEach(author - System.out.println(author.getAge()));注意如果调用空参的sorted()方法需要流中的元素是实现了Comparable。
limit 作用 : 可以设置流的最大长度超出的部分将被抛弃。 例如
对流中的元素按照年龄进行降序排序并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。 ListAuthor authors getAuthors();authors.stream().distinct().sorted().limit(2).forEach(author - System.out.println(author.getName()));skip 作用 : 跳过流中的前n个元素返回剩下的元素。 例如
打印除了年龄最大的作家外的其他作家要求不能有重复元素并且按照年龄降序排序。 ListAuthor authors getAuthors();authors.stream().distinct().sorted().skip(1).forEach(author - System.out.println(author.getName()));(硬核分页)
给大家整个活, 我们既然知道了limit和skip的作用, 那么我们加上一点点细节就可以实现分页功能了(比较硬核) 分页公式 : skip((page-1)*row).limit(row) 其中 page为页数, row为每一页行数
废话不多说, 上代码
//共10条数据, 分2页每页4条数据ListAuthor authors getAuthors();int page 2;int row 5;authors.stream().skip((page-1)*row).limit(row).forEach(s- System.out.println(s));效果如下 flatMap 作用 : map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。 API注释 flatMap操作的效果是对流的元素应用一对多转换然后将生成的元素展平为新的流。
例一
打印所有书籍的名字。要求对重复的元素进行去重。
// 打印所有书籍的名字。要求对重复的元素进行去重。ListAuthor authors getAuthors();authors.stream().flatMap(author - author.getBooks().stream()).distinct().forEach(book - System.out.println(book.getName()));效果如下 例二
打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式哲学,爱情
// 打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式哲学,爱情 爱情ListAuthor authors getAuthors();authors.stream().flatMap(author - author.getBooks().stream()).distinct().flatMap(book - Arrays.stream(book.getCategory().split(,))).distinct().forEach(category- System.out.println(category));终结操作
forEach 作用 : 对流中的元素进行历操作我们通过传入的参数去指定对遍历到的元素进行什么具体操作。 例子
输出所有作家的名字
// 输出所有作家的名字ListAuthor authors getAuthors();authors.stream().map(author - author.getName()).distinct().forEach(name- System.out.println(name));
count 作用 : 可以用来获取当前流中元素的个数。 例子
打印这些作家的所出书籍的数目注意删除重复元素。
// 打印这些作家的所出书籍的数目注意删除重复元素。ListAuthor authors getAuthors();long count authors.stream().flatMap(author - author.getBooks().stream()).distinct().count();System.out.println(count);maxmin 作用 : 可以用来或者流中的最值。 例子
分别获取这些作家的所出书籍的最高分和最低分并打印。
// 分别获取这些作家的所出书籍的最高分和最低分并打印。//StreamAuthor - StreamBook -StreamInteger -求值ListAuthor authors getAuthors();OptionalInteger max authors.stream().flatMap(author - author.getBooks().stream()).map(book - book.getScore()).max((score1, score2) - score1 - score2);OptionalInteger min authors.stream().flatMap(author - author.getBooks().stream()).map(book - book.getScore()).min((score1, score2) - score1 - score2);System.out.println(max.get());System.out.println(min.get());collect 作用 : 把当前流转换成一个集合。 例子
获取一个存放所有作者名字的List集合。
// 获取一个存放所有作者名字的List集合。ListAuthor authors getAuthors();ListString nameList authors.stream().map(author - author.getName()).collect(Collectors.toList());System.out.println(nameList); 获取一个所有书名的Set集合。
// 获取一个所有书名的Set集合。ListAuthor authors getAuthors();SetBook books authors.stream().flatMap(author - author.getBooks().stream()).collect(Collectors.toSet());System.out.println(books); 获取一个Map集合map的key为作者名value为List
// 获取一个Map集合map的key为作者名value为ListBookListAuthor authors getAuthors();MapString, ListBook map authors.stream().distinct().collect(Collectors.toMap(author - author.getName(), author - author.getBooks()));System.out.println(map);查找与匹配
anyMatch 作用 : 可以用来判断是否有任意符合匹配条件的元素结果为boolean类型。 例子
判断是否有年龄在29以上的作家
// 判断是否有年龄在29以上的作家ListAuthor authors getAuthors();boolean flag authors.stream().anyMatch(author - author.getAge() 29);System.out.println(flag);allMatch 作用 : 可以用来判断是否都符合匹配条件结果为boolean类型。如果都符合结果为true否则结果为false。 例子
判断是否所有的作家都是成年人
// 判断是否所有的作家都是成年人ListAuthor authors getAuthors();boolean flag authors.stream().allMatch(author - author.getAge() 18);System.out.println(flag);noneMatch 作用 : 可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true否则结果为false。 例子
判断作家是否都没有超过100岁的。
// 判断作家是否都没有超过100岁的。ListAuthor authors getAuthors();boolean b authors.stream().noneMatch(author - author.getAge() 100);System.out.println(b);findAny 作用 : 获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。 例子
获取任意一个年龄大于18的作家如果存在就输出他的名字
// 获取任意一个年龄大于18的作家如果存在就输出他的名字ListAuthor authors getAuthors();OptionalAuthor optionalAuthor authors.stream().filter(author - author.getAge()18).findAny();optionalAuthor.ifPresent(author - System.out.println(author.getName()));findFirst 作用 : 获取流中的第一个元素。 例子
获取一个年龄最小的作家并输出他的姓名。
// 获取一个年龄最小的作家并输出他的姓名。ListAuthor authors getAuthors();OptionalAuthor first authors.stream().sorted((o1, o2) - o1.getAge() - o2.getAge()).findFirst();first.ifPresent(author - System.out.println(author.getName()));reduce归并 作用 : 对流中的数据按照你指定的计算方式计算出一个结果缩减操作。 reduce的作用是把stream中的元素给组合起来我们可以传入一个初始值它会按照我们的计算方式依次拿流中的元素和初始化值进行计算计算结果再和后面的元素计算。
reduce两个参数的重载形式内部的计算方式如下
T result identity;
for (T element : this stream)result accumulator.apply(result, element)
return result; 其中identity就是我们可以通过方法参数传入的初始值accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
例子
使用reduce求所有作者年龄的和
// 使用reduce求所有作者年龄的和ListAuthor authors getAuthors();Integer sum authors.stream().distinct().map(author - author.getAge()).reduce(0, (result, element) - result element);System.out.println(sum); 使用reduce求所有作者中年龄的最大值
// 使用reduce求所有作者中年龄的最大值ListAuthor authors getAuthors();Integer max authors.stream().map(author - author.getAge()).reduce(Integer.MIN_VALUE, (result, element) - result element ? element : result);System.out.println(max); 使用reduce求所有作者中年龄的最小值
// 使用reduce求所有作者中年龄的最小值ListAuthor authors getAuthors();Integer min authors.stream().map(author - author.getAge()).reduce(Integer.MAX_VALUE, (result, element) - result element ? element : result);System.out.println(min); reduce一个参数的重载形式内部的计算 boolean foundAny false;T result null;for (T element : this stream) {if (!foundAny) {foundAny true;result element;}elseresult accumulator.apply(result, element);}return foundAny ? Optional.of(result) : Optional.empty(); 如果用一个参数的重载方法去求最小值代码如下 // 使用reduce求所有作者中年龄的最小值ListAuthor authors getAuthors();OptionalInteger minOptional authors.stream().map(author - author.getAge()).reduce((result, element) - result element ? element : result);minOptional.ifPresent(age- System.out.println(age));如果这篇【文章】有帮助到你希望可以给我点个赞创作不易如果有对Java后端或者对spring感兴趣的朋友,请多多关注 个人主页 : 阿千弟
文章转载自: http://www.morning.xkpjl.cn.gov.cn.xkpjl.cn http://www.morning.zpkfb.cn.gov.cn.zpkfb.cn http://www.morning.rnqyy.cn.gov.cn.rnqyy.cn http://www.morning.ywpcs.cn.gov.cn.ywpcs.cn http://www.morning.xkpjl.cn.gov.cn.xkpjl.cn http://www.morning.csdgt.cn.gov.cn.csdgt.cn http://www.morning.wqcz.cn.gov.cn.wqcz.cn http://www.morning.hwbmn.cn.gov.cn.hwbmn.cn http://www.morning.bxqtq.cn.gov.cn.bxqtq.cn http://www.morning.mqldj.cn.gov.cn.mqldj.cn http://www.morning.bnfrj.cn.gov.cn.bnfrj.cn http://www.morning.trpq.cn.gov.cn.trpq.cn http://www.morning.qtkdn.cn.gov.cn.qtkdn.cn http://www.morning.cwfkm.cn.gov.cn.cwfkm.cn http://www.morning.bnmrp.cn.gov.cn.bnmrp.cn http://www.morning.bqts.cn.gov.cn.bqts.cn http://www.morning.dwhnb.cn.gov.cn.dwhnb.cn http://www.morning.pgmbl.cn.gov.cn.pgmbl.cn http://www.morning.wqsjx.cn.gov.cn.wqsjx.cn http://www.morning.ddxjr.cn.gov.cn.ddxjr.cn http://www.morning.zlnkq.cn.gov.cn.zlnkq.cn http://www.morning.nwcgj.cn.gov.cn.nwcgj.cn http://www.morning.kqbwr.cn.gov.cn.kqbwr.cn http://www.morning.fyskq.cn.gov.cn.fyskq.cn http://www.morning.drhnj.cn.gov.cn.drhnj.cn http://www.morning.hsflq.cn.gov.cn.hsflq.cn http://www.morning.tqklh.cn.gov.cn.tqklh.cn http://www.morning.rhph.cn.gov.cn.rhph.cn http://www.morning.jqpyq.cn.gov.cn.jqpyq.cn http://www.morning.ztqj.cn.gov.cn.ztqj.cn http://www.morning.pzbjy.cn.gov.cn.pzbjy.cn http://www.morning.pbzlh.cn.gov.cn.pbzlh.cn http://www.morning.ztmnr.cn.gov.cn.ztmnr.cn http://www.morning.prgdy.cn.gov.cn.prgdy.cn http://www.morning.qkgwx.cn.gov.cn.qkgwx.cn http://www.morning.807yy.cn.gov.cn.807yy.cn http://www.morning.hgsylxs.com.gov.cn.hgsylxs.com http://www.morning.lnckq.cn.gov.cn.lnckq.cn http://www.morning.qqbw.cn.gov.cn.qqbw.cn http://www.morning.rbbgh.cn.gov.cn.rbbgh.cn http://www.morning.rjqtq.cn.gov.cn.rjqtq.cn http://www.morning.tbnpn.cn.gov.cn.tbnpn.cn http://www.morning.bxyzr.cn.gov.cn.bxyzr.cn http://www.morning.gcspr.cn.gov.cn.gcspr.cn http://www.morning.iiunion.com.gov.cn.iiunion.com http://www.morning.rzrbw.cn.gov.cn.rzrbw.cn http://www.morning.krhkn.cn.gov.cn.krhkn.cn http://www.morning.srhqm.cn.gov.cn.srhqm.cn http://www.morning.tlrxt.cn.gov.cn.tlrxt.cn http://www.morning.rnsjp.cn.gov.cn.rnsjp.cn http://www.morning.plcyq.cn.gov.cn.plcyq.cn http://www.morning.tqqfj.cn.gov.cn.tqqfj.cn http://www.morning.yxnfd.cn.gov.cn.yxnfd.cn http://www.morning.fqqcn.cn.gov.cn.fqqcn.cn http://www.morning.cykqg.cn.gov.cn.cykqg.cn http://www.morning.htqrh.cn.gov.cn.htqrh.cn http://www.morning.jwxmn.cn.gov.cn.jwxmn.cn http://www.morning.kqwsy.cn.gov.cn.kqwsy.cn http://www.morning.xctdn.cn.gov.cn.xctdn.cn http://www.morning.fwwkr.cn.gov.cn.fwwkr.cn http://www.morning.jllnh.cn.gov.cn.jllnh.cn http://www.morning.pqwrg.cn.gov.cn.pqwrg.cn http://www.morning.xctdn.cn.gov.cn.xctdn.cn http://www.morning.ylklr.cn.gov.cn.ylklr.cn http://www.morning.kbdrq.cn.gov.cn.kbdrq.cn http://www.morning.rhsg.cn.gov.cn.rhsg.cn http://www.morning.snbq.cn.gov.cn.snbq.cn http://www.morning.ldmtq.cn.gov.cn.ldmtq.cn http://www.morning.bwygy.cn.gov.cn.bwygy.cn http://www.morning.ghpld.cn.gov.cn.ghpld.cn http://www.morning.benqc.com.gov.cn.benqc.com http://www.morning.rcmwl.cn.gov.cn.rcmwl.cn http://www.morning.zrgdd.cn.gov.cn.zrgdd.cn http://www.morning.zdqsc.cn.gov.cn.zdqsc.cn http://www.morning.zwpzy.cn.gov.cn.zwpzy.cn http://www.morning.mglqf.cn.gov.cn.mglqf.cn http://www.morning.dbjyb.cn.gov.cn.dbjyb.cn http://www.morning.ksgjn.cn.gov.cn.ksgjn.cn http://www.morning.fygbq.cn.gov.cn.fygbq.cn http://www.morning.mdtfh.cn.gov.cn.mdtfh.cn