当前位置: 首页 > 后端技术 > Java

Java8特性

时间:2023-04-01 19:22:27 Java

publicclassUserPo{privateStringname;私人双倍分数;//省略构造函数和getter,setter}filterfilter:filter,就是过滤器,合格通过,不合格过滤掉//filter成绩不为空的学生人数count=list.stream().filter(p->null!=p.getScore()).count();mapmap:映射,将原始集合映射到新集合,在VO和PO处理过程中比较常见。本例中原集合为PO集合,新集合可以自定义映射为成绩集合,也可以对新集合进行相关操作//取出所有学生的成绩ListscoreList=list.stream().map(p->p.getScore()).collect(Collectors.toList());//将学生姓名集合串成字符串,以逗号分隔StringnameString=list.stream().map(p->p.getName()).collect(Collectors.joining(","));sortedsorted:排序,可以按照指定的字段进行排序//如果按照倒序对学生进行排序对于成绩,您不需要添加.reversed()filterList=list.stream().filter(p->null!=p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());forEachforEach:这个应该是最常用的,即对每个元素进行自定义操作除了forEach操作会改变原集合的数据,其他操作都会不改变原来的集合,这点一定要注意//学生成绩太差,通过率太低,给每个学生加10分,放一个水//forEachfilterList.stream().forEach(p->p.setScore(p.getScore()+10));collectcollect:聚合,可用于GroudBy按指定字段分类,也可用于返回列表或拼凑字符串//GroupbyscoreMap>groupByScoreMap=list.stream().filter(p->null!=p.getScore()).collect(Collectors.groupingBy(UserPo::getScore));for(Map.Entry>entry:groupByScoreMap.entrySet()){System.out.println("分数:"+entry.getKey()+"人数:"+entry.getValue().size());}//returnlistListscoreList=list.stream().map(p->p.getScore()).collect(Collectors.toList());//返回字符串,用逗号分隔StringnameString=list.stream().map(p->p.getName()).collect(Collectors.joining(","));statisticsstatistics:统计,可以统计中位数、平均值、最大值和最小值DoubleSummaryStatisticsstatistics=filterList.stream().mapToDouble(p->p.getScore()).summaryStatistics();System.out.println("The列表中最大的数字:"+statistics.getMax());System.out.println("列表中最小的数:"+statistics.getMin());System.out.println("所有数的总和:"+statistics.getSum());System.out.println("Average:"+statistics.getAverage());parallelStreamparallelStream:并行流,可以使用多个Thread进行流操作,提高效率但是它没有线程传播,所以需要充分评估是否需要使用并行流操作//parallelstreamcount=list.parallelStream().filter(p->null!=p.getScore())。count();练习学生stuA=newStudent(1,"A","M",184);StudentstuB=newStudent(2,"B","G",163);StudentstuC=newStudent(3,"C","M",175);学生stuD=newStudent(4,"D","G",158);StudentstuE=newStudent(5,"A","M",158);//stream-forEach循环list.stream().forEach(stu->System.out.println("stream-forEach:"+stu.getName()));//stream-filter过滤就是执行逻辑longcount=list.stream().filter(stu->stu.height>180).count();list.stream().filter(stu->stu.height>180).forEach(stu->System.out.println("stream-filter:"+stu));//Stream-toMap为了避免key冲突,(key1,key2)->key1表示前者Mapmaps=list.stream().collect(Collectors.toMap(Student::getName,Function.identity(),(key1,key2)->key1));System.out.println("key-object"+maps);MapnewMaps=list.stream().collect(Collectors.toMap(Student::getName,Student::getHeight,(key1,key2)->key1));//分流去重+指定字段去重publicclassStreamUtil{/***指定字段去重*@paramkeyExtractor*@return*/staticPredicatedistinctByKey(FunctionkeyExtractor){Mapseen=新的ConcurrentHashMap<>();returnt->seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)==null;}}System.out.println("************Stream-distincttoTheequals和哈希码方法必须重写*************");list.stream().distinct().forEach(b->System.out.println("Stream-distinctdeduplication"+b.getName()+","+b.getHeight()));list.stream().filter(StreamUtil.distinctByKey(b->b.getSex())).forEach(b->System.out.println("Stream-distinct指定字段去重"+b.getName()+","+b.getSex()));//过滤后得到一个新的集合ListnewList=list.stream().filter(stu->stu.height>165).collect(Collectors.toList());System.out.println("新集合:"+newList);//流式聚合操作最大值、最小值System.out.println("**************流式聚合操作最大值、最小值*************");System.out.println("sum:"+list.stream().mapToDouble(Student::getHeight).sum());System.out.println("max:"+list.stream().mapToDouble(Student::getHeight).max().getAsDouble());System.out.println("min:"+list.stream().mapToDouble(Student::getHeight).min().getAsDouble());System.out.println("avg:"+list.stream().mapToDouble(Student::getHeight).average().getAsDouble());//流排序系统.out.println("**************stream-聚合操作排序************");Listcollect=list.stream().filter(stu->stu.getHeight()>165).sorted((e1,e2)->Float.compare(e1.getHeight(),e2.getHeight())).collect(Collectors.toList());System.out.println("stream顺序"+collect);}练习2publicstaticvoidmain(String[]args){Listtransactions=null;Traderraoul=newTrader("Raoul","Cambridge");Tradermario=newTrader("Mario","Milan");Traderalan=newTrader("Alan","Cambridge");Traderbrian=newTrader("Brian","Cambridge");transactions=Arrays.asList(newTransaction(brian,2011,300),新交易(raoul,2012,1000),新交易(raoul,2011,400),新交易(mario,2012,400),新交易(mario,2012,710),新交易(alan,2012,950));//①找出2011年发生的所有交易,按交易金额从低到高排序//方法一:Longbegin=System.currentTimeMillis();ListnewTr=transactions.stream().filter(tran->tran.getYear()==2011).collect(Collectors.toList());newTr.sort(Comparator.comparing(t->t.getValue()));长端=System.currentTimeMillis();System.out.println("耗时:"+(end-begin)+""+newTr);//方法二:差距大概是35倍!Longbegin2=System.currentTimeMillis();Listcollect=transactions.stream().filter(tran->tran.getYear()==2011).sorted((e1,e2)->Integer.compare(e1.getValue(),e2.getValue())).collect(Collectors.toList());Longend2=System.currentTimeMillis();System.out.println("耗时:"+(end2-begin2)+""+收集);//②交易员在哪些不同的城市工作过?//方法1:transactions.stream().filter(StreamUtil.distinctByKey(tran->tran.getTrader().getCity())).collect(Collectors.toList()).forEach(t->System.out.println(t.getTrader().getCity()));//方法2:ListcollCityTwo=transactions.stream().map(e->e.getTrader().getCity()).distinct().collect(Collectors.toList());System.out.println("城市是:"+collCityTwo);//③查找来自剑桥的所有交易员并按名称排序:getTrader).sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());System.out.println(collPerson);//⑤米兰有交易员吗?longcount=transactions.stream().filter(tran->tran.getTrader().getCity().equals("米兰")).count();System.out.println("有没有人在米兰工作:"+(count>0));//⑥打印居住在剑桥的交易员的所有交易总和intsum=transactions.stream().filter(e->e.getTrader().getCity().equals("Cambridge")).mapToInt(Transaction::获取值).sum();System.out.println("总计为:"+sum);//⑦所有交易中最高的交易金额是多少intmax=transactions.stream().mapToInt(Transaction::getValue).max().getAsInt();System.out.println("最大值为:"+max);//⑧找到交易金额最小的交易Transactiontransaction=transactions.stream().min((e1,e2)->Integer.compare(e1.getValue(),e2.getValuee())).get();System.out.println("最小值交易是:"+transaction);}}classTrader{privateStringname;privateStringcity;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicStringgetCity(){returncity;}publicvoidsetCity(Stringcity){this.city=city;}@OverridepublicStringtoString(){return"Trader[name="+name+",city="+city+"]";}publicTrader(Stringname,Stringcity){super();this.name=名称;this.city=city;}}classTransaction{privateTradertrader;privateintyear;privateintvalue;publicTradergetTrader(){returntrader;}publicvoidsetTrader(Tradertrader){this.trader=trader;}publicintgetYear(){returnyear;}publicvoidsetYear(intyear){this.year=year;}publicintgetValue(){返回值;}publicvoidsetValue(intvalue){this.value=valuee;}@OverridepublicStringtoString(){return"Transaction[trader="+trader+",year="+year+",value="+value+"]";}publicTransaction(Tradertrader,intyear,整数值){超级();this.trader=交易员;this.year=年;this.value=值;}}