介绍Java8已经出来很久了。接口的默认方法、lambda表达式、函数式接口、DateAPI等特性还是很有必要了解的。比如项目中经常用到集合,遍历集合可以尝试lambda表达式,经常需要对集合进行过滤排序,Stream就派上用场了。我已经习惯了,不得不说它真的好用。Stream作为java8的新特性,基于lambda表达式,是对集合对象功能的增强。它专注于对集合对象进行各种高效便捷的聚合操作或大规模数据操作,提高了编程效率和代码可读性。性别。Stream的原理:把要处理的元素看成一个流,在管道中传输,可以在管道的节点上进行处理,包括过滤、去重、排序、聚合等。元素流由中间体处理流水线中的操作,最终最后的操作得到前面处理的结果。有两种方法可以为集合生成流:stream()-为集合创建串行流parallelStream()-为集合创建并行流上图是Stream类的类结构图,其中包含了大部分中间和终止操作。中间操作主要有以下方法(此类方法返回Stream):map(mapToInt、flatMap等)、filter、distinct、sorted、peek、limit、skip、parallel、sequential、unordered。终止操作主要有以下方法:forEach,forEachOrdered,toArray,reduce,collect,min,max,count,anyMatch,allMatch,noneMatch,findFirst,findAny,iterator举例首先,为了说明Stream对对象集合,新建一个Student类(学生类),覆盖equals()和hashCode()方法id=id;this.name=name;this.age=age;this.address=address;}@OverridepublicStringtoString(){return"Student{"+"id="+id+",name='"+name+'\''+",age="+age+",address='"+address+'\''+'}';}@Overridepublicbooleanequals(Objecto){if(this==o)returntrue;if(o==null||getClass()!=o.getClass())returnfalse;学生学生=(学生)o;return==student.age&&Objects.equals(id,student.id)&&Objects.equals(姓名,学生ent.name)&&Objects.equals(address,student.address);}@OverridepublicinthashCode(){returnObjects.hash(id,name,age,address);}publicLonggetId(){returnid;}publicvoidsetId(Longid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}publicStringgetAddress(){returnaddress;}publicvoidsetAddress(Stringaddress){this.address=address;}}filter(筛选)publicstaticvoidmain(String[]args){Students1=newStudent(1L,"肖战",15,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨紫",17,"北京");Students4=newStudent(4L,"李现",17,"浙江");List学生=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);ListstreamStudents=testFilter(students);streamStudents.forEach(System.out::println);}/***集合的筛选*@paramstudents*@return*/privatestaticListtestFilter(Liststudents){//过滤15岁以上的学生//returnsstudents.stream().filter(s->s.getAge()>15).collect(Collectors.toList());//筛选浙江省学生returnsstudents.stream().filter(s->"Zhejiang".equals(s.getAddress())).collect(Collectors.toList());}运行结果:这里我们创建了四个学生,通过filter过滤后,我们筛选出了地址为浙江的学生集合map(conversion)publicstaticvoidmain(String[]args){Students1=newStudent(1L,"肖战",15,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨子",17,"北京");Students4=newStudent(4L,"李现",17,"浙江");Liststudents=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);testMap(students);}/***集合转换*@paramstudents*@return*/privatestaticvoidtestMap(Liststudents){//地址前面加一些信息,只获取地址输出Listaddresses=students.stream().map(s->"Address:"+s.getAddress())。collect(Collectors.toList());addresses.forEach(a->System.out.println(a));}运行结果图就是将对应的元素按照给定的方法进行转换。distinct(deduplication)publicstaticvoidmain(String[]args){testDistinct1();}/***setdeduplication(basictype)*/privatestaticvoidtestDistinct1(){//简单字符串去重Listlist=Arrays.asList("111","222","333","111","222");list.stream().distinct().forEach(System.out::println);}运行结果:publicstaticvoidmain(String[]args){testDistinct2();}/***Setdeduplication(referenceobject)*/privatestaticvoidtestDistinct2(){//引用对象去重,引用对象必须实现hashCode和equal方法,否则去重无效Students1=newStudent(1L,"肖战",15,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨紫",17,"北京");Students4=newStudent(4L,"李现",17,"浙江");Students5=newStudent(1L,"肖战",15,"浙江");Liststudents=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);students.add(s5);students.stream().distinct().forEach(System.out::println);}运行结果:可以看出两人重复了“肖战”这不仅仅是因为使用了distinct()方法,还因为Student对象重写了equals和hashCode()方法,否则去重无效sorted(排序)publicstaticvoidmain(String[]args){testSort1();}/***集合排序(默认排序)*/privatestaticvoidtestSort1(){Listlist=Arrays.asList("333","222","111");list.stream().sorted().forEach(System.out::println);}运行结果:publicstaticvoidmain(String[]args){testSort2();}/***集合排序(指定排序规则)*/privatestaticvoidtestSort2(){Students1=newStudent(1L,"肖战",15,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨子",17,"北京");Students4=newStudent(4L,"李现",17,"浙江");Liststudents=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);students.stream().sorted((stu1,stu2)->Long.compare(stu2.getId(),stu1.getId())).sorted((stu1,stu2)->Integer.compare(stu2.getAge(),stu1.getAge())).forEach(System.out::println);}运行结果:上面指定的排序规则,先按学号降序排序,再按年龄限制降序排序(限制返回次数)publicstaticvoidmain(String[]args){testLimit();}/***集合限制,返回前几个元素*/privatestaticvoidtestLimit(){Listlist=Arrays.asList("333","222","111");list.stream().limit(2).forEach(System.out::println);}运行结果:skip(删除元素)publicstaticvoidmain(String[]args){testSkip();}/***collectionskip,删除前n个元素*/privatestaticvoidtestSkip(){Listlist=Arrays.asList("333","222","111");list.stream().skip(2).forEach(System.out::println);}运行结果:reduce(aggregation)publicstaticvoidmain(String[]args){testReduce();}/***集合reduce,将集合中的每个元素聚合成一条数据*/privatestaticvoidtestReduce(){Listlist=Arrays.asList("欢","欢迎","你");StringappendStr=list.stream().reduce("北京",(a,b)->a+b);System.out.println(appendStr);}运行结果:min(最小值)publicstaticvoidmain(String[]args){testMin();}/***求集合中元素的最小值*/privatestaticvoidtestMin(){梭哈ents1=newStudent(1L,"肖战",14,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨子",17,"北京");Students4=newStudent(4L,"李县",17,"浙江");Liststudents=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);StudentminS=students.stream().min((stu1,stu2)->整数.compare(stu1.getAge(),stu2.getAge())).get();System.out.println(minS.toString());}运行结果:上面是在所有学生中找最小的,max同理,求最大值anyMatch/allMatch/noneMatch(match)publicstaticvoidmain(String[]args){testMatch();}privatestaticvoidtestMatch(){Students1=newStudent(1L,"肖战",15,"浙江");Students2=newStudent(2L,"王一博",15,"湖北");Students3=newStudent(3L,"杨紫",17,"北京");Students4=newStudent(4L,"李现",17,"浙江");List<学生>students=newArrayList<>();students.add(s1);students.add(s2);students.add(s3);students.add(s4);BooleananyMatch=students.stream().anyMatch(s->"湖北".equals(s.getAddress()));if(anyMatch){System.out.println("有湖北人");}BooleanallMatch=students.stream().allMatch(s->s.getAge()>=15);if(allMatch){System.out.println("所有学生都超过15岁");}BooleannoneMatch=students.stream().noneMatch(s->"杨洋".equals(s.getName()));if(noneMatch){System.out.println("没有叫杨杨的同学");}}运行结果:anyMatch:Stream中的任意元素匹配传入的predicate,returntrueallMatch:Stream中的所有元素匹配中的coming谓词返回truenoneMatch:Stream中没有元素匹配传入的predicate,返回true总结了Stream的一些常用方法。虽然对集合的遍历和操作可以按照通常的方式进行,但是当业务逻辑复杂的时候,你会发现代码量很大,可读性差。明明一行代码解决问题,你却写几行来试试lambda表达式和Stream。你会有不一样的体验。