乐鱼娱乐体育

- 欢迎访问乐鱼娱乐体育-乐鱼娱乐体育官方入口

乐鱼娱乐 Java8新特质

时间:2023-01-10 12:46 点击:73 次

接口中默许方法修饰为闲居方法

在jdk8之前,interface之中不错界说变量和方法,变量必须是public、static、final的,方法必须是public、abstract的,由于这些修饰符都是默许的。

接口界说方法:public抽象方法需要子类完了

接口界说变量:public、static、final

在JDK1.8运转辅助使用static和default修饰不错写方法体,不需要子类重写。

方法:

闲居方法不错有方法体

抽象方法莫得方法体需要子类完了重写。

案例

publicinterfaceJDK8Interface{/**默许等于publicabstractJDK7之前不成有方法体**/voidadd;/**jdk8提供默许完了**/defaultvoidget{System.out.println("default方法不错写方法体");}staticvoidgetStaticOrder{System.out.println("静态方法不错写方法体");}}

子类完了接口

publicclassJDK8InterfaceImplimplementsJDK8Interface{/**子类完了接口莫得强制要求重写default和static方法**/@Overridepublicvoidadd{System.out.println("add方法");}}

方法调用

publicclassTest01{publicstaticvoidmain(String[]args){JDK8Interfacejdk8Interface=newJDK8InterfaceImpl;jdk8Interface.add;jdk8Interface.get;JDK8Interface.getStaticOrder;}}

Lambda抒发式

是一个匿名函数,简化咱们调用匿名函数的经由

Lambda刚正:简化咱们匿名里面类的调用。

Lambda+方法引入代码变得愈加精简。

publicstaticvoidmain(String[]args){//使用匿名里面类的面孔调用//newOrderService{//@Override//publicvoidaddOrder{//System.out.println("addorder");//}//}.addOrder;((OrderService)->System.out.println("addorder")).addOrder;//newThread(newRunnable{//@Override//publicvoidrun{//System.out.println(Thread.currentThread.getName+"运行");//}//}).start;newThread(->System.out.println(Thread.currentThread.getName+"运行")).start;}

Lambda抒发式的活动

使用Lambda抒发式依赖于函数接口

在接口中只约略允许有一个抽象方法

在函数接口中界说object类中方法

使用默许或者静态方法

@FunctionalInterface默示该接口为函数接口

对于星爷的实力,在圈中的人都很给他面子,基本他想请的人,不管实力有多高,他都有能力将他请到自己剧组,就好比说冯小刚。他可是赫赫有名的大导演,想当年星爷邀请他来出演《功夫》这部影片,虽然名气没他大,但冯小刚还是很给面子的去了,轻轻松松就请来了,虽然冯小刚在周星驰电影开头客串了几分钟,但也成为了经典,尤其是他的几句台词,还成了当今的网络流行词语。

Java中使用Lambda抒发式的活动,必须是为函数接口

函数接口的界说:在该接口中只可存在一个抽象方法,该接口称算作函数接口

@FunctionalInterfacepublicinterfaceMyFunctionalInterface{voidget;defaultvoidadd{}StringtoString;}

常见举例Runnable接口

方法调用

publicstaticvoidmain(String[]args){((MyFunctionalInterface)->System.out.println).get;}

Lambda基础语法

--参数列表->分隔{}方法体

(函数接口的参数列表不需要写类型需要界说参数称号)->{方法体}

无参方法调用

@FunctionalInterfacepublicinterfaceMyFunctionalInterface{voidget;}MyFunctionalInterfacemyFunctionalInterface=->{System.out.println("使用lambda抒发式");};

有参带复返值调用

@FunctionalInterfacepublicinterfaceYouFunctionalInterface{Stringget(inti,intj);}

publicstaticvoidmain(String[]args){YouFunctionalInterfaceyouFunctionalInter=(i,j)->{returni+"--"+j;};System.out.println(youFunctionalInter.get(1,1));}

精简版

publicstaticvoidmain(String[]args){//无参方法原始版块MyFunctionalInterfacefunctionalInterface=->{System.out.println("");};functionalInterface.get;//精简版1((MyFunctionalInterface)->{System.out.println("");}).get;//精简版2在方法体只消一条语句的期间,不需要写大括号了MyFunctionalInterfacefunctionalInterface2=->System.out.println("");//最终精简版3((MyFunctionalInterface)->System.out.println("")).get;//有参方法YouFunctionalInterfaceyouFunctionalInterface=(inti,intj)->{return"";};Strings=youFunctionalInterface.get(2,3);//精简版1YouFunctionalInterfaceyouFunctionalInterface1=(i,j)->{return"";};//精简版2YouFunctionalInterfaceyouFunctionalInterface2=(i,j)->i+"--"+j;Strings1=youFunctionalInterface1.get(2,3);//最终精简版3Strings2=((YouFunctionalInterface)(i,j)->i+"--"+j).get(1,2);System.out.println(s2);}

Lambda实战案例

Foreach

publicstaticvoidmain(String[]args){ArrayListarrayList=newArrayList;arrayList.add("111");arrayList.add("222");arrayList.add("333");//arrayList.forEach(newConsumer{//@Override//publicvoidaccept(Strings){//System.out.println(s);//}//});arrayList.forEach(s->{System.out.println(s);});}

Lambda齐集排序

publicclassUserEntity{privateStringname;privateIntegerage;publicUserEntity(Stringname,Integerage){this.name=name;this.age=age;}publicStringgetName{returnname;}publicIntegergetAge{returnage;}@OverridepublicStringtoString{return"UserEntity{"+"name='"+name+'\''+",age="+age+'}';}}

publicstaticvoidmain(String[]args){ArrayListuserlists=newArrayList;userlists.add(newUserEntity("aa",22));userlists.add(newUserEntity("bb",18));userlists.add(newUserEntity("cc",36));userlists.sort(newComparator{@Overridepublicintcompare(UserEntityo1,UserEntityo2){returno1.getAge-o2.getAge;}});//精简遍历userlists.forEach(s->System.out.println(s));//精简排序userlists.sort((o1,o2)->o1.getAge-o2.getAge);}

Java8stream流

Stream是JDK1.8中处理齐集的关键抽象办法,Lambda和Stream是JDK1.8新增的函数式编程最有亮点的特质了,它不错指定你但愿对齐集进行的操作,不错试验格外复杂的查找、过滤和映射数据等操作。使用StreamAPI对齐集数据进行操作,就一样于使用SQL试验的数据库查询。Stream使用一种一样用SQL语句从数据库查询数据的直觉面孔来提供一种对Java齐集运算和抒发的高阶抽象。StreamAPI不错极大擢升Java口头员的出产力,让口头员写出高后果、干净、简略的代码

这种作风将要处理的元素齐集看作一种流,流在管道中传输,何况不错在管道的节点上进行处理,比如筛选,排序,团聚等

Stream:格外便捷精简的体式遍历齐集完了过滤、排序等

Stream创建面孔

parallelStream为并行流接纳多线程试验

Stream接纳单线程试验

parallelStream后果比Stream要高

Stream将list疏导为set

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;Setcollect=stream.collect(Collectors.toSet);collect.forEach(s->System.out.println(s));}

set齐集底层依赖于map齐集,map齐集底层基于equals和hashcode相比详确叠加

Stream将list疏导为map

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));/**list齐集只消keylist疏导map的期间需要指定keyvalue,key=usernamevalue=user对象**/Streamstream=userEntities.stream;Mapcollect=stream.collect(Collectors.toMap(newFunction{@OverridepublicStringapply(UserEntityo){returno.getName;}},newFunction{@OverridepublicUserEntityapply(UserEntityusrentity){returnusrentity;}}));//精简版collect.forEach(newBiConsumer{@Overridepublicvoidaccept(Strings,UserEntityuserEntity){System.out.println(s+","+userEntity);}});//最终精简版collect.forEach((BiConsumer)(s,userEntity)->System.out.println(s+","+userEntity));}

Stream将Reduce乞降

publicstaticvoidmain(String[]args){StreamintegerStream=Stream.of(5,6,7,8);Optionalreduce=integerStream.reduce(newBinaryOperator{@OverridepublicIntegerapply(Integerinteger,Integerinteger2){returninteger+integer2;}});System.out.println(reduce);ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Optionalsum=userEntities.stream.reduce(newBinaryOperator{@OverridepublicUserEntityapply(UserEntityuserEntity,UserEntityuserEntity2){UserEntityuserEntity1=newUserEntity("sum",userEntity.getAge+userEntity2.getAge);returnuserEntity1;}});System.out.println(sum);}

Stream求最大最小

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;Optionalmin=stream.min(newComparator{@Overridepublicintcompare(UserEntityo1,UserEntityo2){returno1.getAge-o2.getAge;}});System.out.println(min.get);//简化版Optionalmin1=stream.min((o1,o2)->o1.getAge-o2.getAge);System.out.println(min1.get);}

StreamMatch匹配

anyMatch默示,判断的条目里,任性一个元素胜利,复返true

allMatch默示,判断条目里的元素,统共的都是,复返true

noneMatch跟allMatch相背,判断条目里的元素,统共的都不是,复返true

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;booleanb=stream.anyMatch(newPredicate{@Overridepublicbooleantest(UserEntityuserEntity){return"aa".equals(userEntity.getName);}});System.out.println(b);//简化版booleanb1=stream.anyMatch((userEntity)->"aa".equals(userEntity.getName));System.out.println(b1);}

Streamfor轮回

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;stream.forEach((userEntity->System.out.println(userEntity)));}

Streamfilter过滤器

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;stream.filter(newPredicate{@Overridepublicbooleantest(UserEntityuserEntity){return"aa".equals(userEntity.getName)&&userEntity.getAge>=18;}}).forEach((userEntity->System.out.println(userEntity)));//精简版stream.filter((userEntity)->"aa".equals(userEntity.getName)&&userEntity.getAge>=18).forEach((userEntity->System.out.println(userEntity)));}

Streamlimit和skip

Limit从新运转取得

Skip等于跳过

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("aa",20));userEntities.add(newUserEntity("bb",28));userEntities.add(newUserEntity("cc",35));userEntities.add(newUserEntity("dd",16));Streamstream=userEntities.stream;stream.skip(2).limit(2).forEach((userEntity->System.out.println(userEntity)));}

stream概括案例

publicstaticvoidmain(String[]args){ArrayListuserEntities=newArrayList;userEntities.add(newUserEntity("mayikt",20));userEntities.add(newUserEntity("meite",28));userEntities.add(newUserEntity("zhangsan",35));userEntities.add(newUserEntity("xiaowei",16));userEntities.add(newUserEntity("mayikt_list",109));userEntities.add(newUserEntity("mayikt_zhangsan",110));userEntities.add(newUserEntity("lisi",109));userEntities.add(newUserEntity("mayikt",100));userEntities.add(newUserEntity("mayikt",60));Streamstream=userEntities.stream;stream.sorted((o1,o2)->o1.getAge-o2.getAge).filter((userEntity->"mayikt".equals(userEntity.getName))).limit(3).forEach((userEntity)->System.out.println(userEntity));}

并行流与串行流分歧

串行流:单线程的面孔操作;数据量相比少的期间。

并行流:多线程面孔操作;数据量相比大的期间

旨趣:Forkjoin将一个大的任务拆分n多个小的子任务并行试验,终末在统计死心,有可能会格外花消cpu的资源,如实不错擢升后果。

正式:数据量相比少的情况下,不要使用并行流

方法援用

什么是方法引入

方法引入:需要聚合lambda抒发式约略让代码变得愈加精简

静态方法引入:类名::(静态)方法称号

对象方法引入类名::实例方法称号

实例方法引入new对象对象实例::方法引入

构造函数引入类名::new

需要罢免一个活动:

方法引入方法参数列表、复返类型与函数接口参数列表与复返类型必须要保持一致。

静态方法引入

/**静态方法引入**/publicclassTest01{publicstaticvoidmain(String[]args){MyFunctionalInterfacemyFunctionalInterface=->{/*引入getStaticMethod方法*/Test01.getStaticMethod;};myFunctionalInterface.get;//使用方法引入调用方法必须甘心:方法引入的方法必须和函数接口中的方法参数列表/复返值一定保持一致。MyFunctionalInterfacemessageInterface=Test01::getStaticMethod;messageInterface.get;}publicstaticvoidgetStaticMethod{System.out.println("我是getMethod");}}

实例对象方法引入

publicclassTest02{publicstaticvoidmain(String[]args){Test02test02=newTest02;MyFunctionalInterfacemyFunctionalInterface=->{/*引入getStaticMethod方法*/test02.getStaticMethod;};myFunctionalInterface.get;//精简版MyFunctionalInterfacemessageInterface=test02::getStaticMethod;messageInterface.get;}publicvoidgetStaticMethod{System.out.println("我是getMethod2");}}

构造函数引入

publicstaticvoidmain(String[]args){UserInterfaceuserInterface=newUserInterface{@OverridepublicUserEntitygetUser{returnnewUserEntity;}};//精简版UserInterfaceuserInterface3=UserEntity::new;userInterface2.getUser;}

对象方法引入

publicclassTest04{publicstaticvoidmain(String[]args){Myservicemyservice=newMyservice{@OverridepublicStringget(Test04test04){returntest04.objGet;}};Myservicemyservice1=(Test04->Test04.objGet);//精简版传入Test04复返string值Myservicemyservice2=Test04::objGet;Functionfunction=newFunction{@OverridepublicIntegerapply(Strings){returns.length;}};//精简版Functionfunction2=String::length;System.out.println(function2.apply("dfdf"));}@FunctionalInterfacepublicinterfaceMyservice{Stringget(Test04userEntity);}

JDK8Optional

Optional类是一个不错为null的容器对象。若是值存在则isPresent方法会复返true,调用get方法会复返该对象。

Optional是个容器:它不错保存类型T的值,或者只是保存null。Optional提供许多灵验的方法,这么咱们就毋庸显式进行空值检测。

Optional类的引入很好的贬责空指针特别。

判断参数是否为空

ofNullable(不错传递一个空对象)

Of(不不错传递空对象)

publicstaticvoidmain(String[]args){Stringusername=null;Integera1=1;Optionala=Optional.ofNullable(a1);System.out.println(a.isPresent);//trueOptionalusername1=Optional.ofNullable(username);System.out.println(username1.isPresent);//false}

isPresent默示死心复返是否为空,true不为空,复返false为空

参数为空不错设定默许值

publicstaticvoidmain(String[]args){Integera1=null;Integera=Optional.ofNullable(a1).orElse(10);System.out.println(a);//10}

参数完了过滤

publicstaticvoidmain(String[]args){Integera1=16;Optionala=Optional.ofNullable(a1);//判断是否等于16booleanpresent=a.filter(newPredicate{@Overridepublicbooleantest(Integerinteger){returninteger.equals(16);}}).isPresent;System.out.println(present);//truebooleanisPresent=a.filter(a2->a2==17).isPresent;System.out.println(isPresent);//false}

与Lambda抒发式聚合使用,优化代码

优化决策1

publicstaticvoidmain(String[]args){//优化前Stringname="meite";if(name!=null){System.out.println(name);}//优化后Optionalname2=Optional.ofNullable(name);//当value不为空时,则不会调用name2.ifPresent(s->System.out.println(s));name2.ifPresent(System.out::print);}

优化决策2

publicclassTest05{privatestaticUserEntityuserEntity=null;publicstaticvoidmain(String[]args){UserEntityuserEntity=Test05.getOrder;System.out.println(userEntity);}publicstaticUserEntitygetOrder{//优化前if(userEntity==null){returncreateOrder;}returnuserEntity;//优化1returnOptional.ofNullable(Test05.userEntity).orElseGet(newSupplier{@OverridepublicUserEntityget{returncreateOrder;}});//优化2returnOptional.ofNullable(Test05.userEntity).orElseGet(->{Test05.userEntity=createOrder;returnTest05.userEntity;});//精简版returnOptional.ofNullable(Test05.userEntity).orElseGet(->createOrder);}privatestaticUserEntitycreateOrder{returnnewUserEntity("ylc",12);}}

优化决策3

publicclassTest06{publicstaticvoidmain(String[]args){StringorderName=Test06.getOrderName;System.out.println(orderName);}publicstaticStringgetOrderName{//优化前写法:UserEntityuserEntity=newUserEntity("123456"乐鱼娱乐,19);if(userEntity!=null){StringuserEntityName=userEntity.getName;if(userEntityName!=null){returnuserEntityName.toLowerCase;}}//优化后Optionals1=Optional.ofNullable(userEntity).map((s)->s.getName).map((s)->s.toLowerCase);returns1.get;}}

乐鱼娱乐体育官方入口服务热线
官方网站:http://www.51miffy.com/
工作时间:周一至周六(09:00-18:00)
联系我们
QQ:2852320325
邮箱:w365jzcom@qq.com
地址:武汉东湖新技术开发区光谷大道国际企业中心
关注公众号

Powered by 乐鱼娱乐体育-乐鱼娱乐体育官方入口 RSS地图 HTML地图

乐鱼娱乐体育官方入口
乐鱼娱乐体育-乐鱼娱乐体育官方入口-乐鱼娱乐 Java8新特质