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

【Java基础16】不可变集合、流和异常

时间:2023-04-01 17:35:22 Java

1.不可变集合无法更改。在整个使用生命周期中,集合自创建之日起将保持不变。如果你试图修改它,将会报错。出于实施原因、更好的防御以及从不受信任的库调用时,不可变形式更安全。1.1CreateList、Set、Map等接口中提供了静态方法来创建,创建的集合不能修改、添加、删除。publicclassDemo{publicstaticvoidmain(String[]args){//创建一个不可变列表ListlisOf=List.of(1,2,3,4);//只能获取,不能删除,改增System.out.println(lisOf.get(0));//2.ImmutableSet集合,jdk版本需高于8//Setnames=Set.of("迪丽热巴","迪丽热酒","Malzaha","KarlBlink");//names.add("三少爷");//System.out.println(名称);//3.ImmutableMap集合,jdk版本需要高于8//Mapmaps=Map.of("huawei",2,"JavaDevelopment",1,"Watch",1);//maps.put("衣服",3);//System.out.println(地图);}}2。JDK8之后,得益于Lambda表达式的函数式编程,引入了Stream流。它简化了集合和数字的操作。//示例publicclassStreamTest{publicstaticvoidmain(String[]args){ArrayListarrayList=newArrayList<>();Collections.addAll(arrayList,"李小龙","成龙","李连杰","李莲英","叶问","沉腾");//传统方法System.out.println("传统方法");for(inti=0;i=3){System.out.println(s);}}//流方法System.out.println("Stream");Streamstream=arrayList.stream();stream.filter(s->s.startsWith("Li")).filter(s->s.length()>=3).forEach(s->System.out.println(s));}}2.1Stream流的创建已经成功使用,一共分为三个阶段:获取流:获取'pipeline'操作集和值的中间操作:类似于'pipeline'上的操作,运行结束后,可以继续后续的运行终止方法:一个管道只有一个终止方法,一旦执行完这个方法,管道就会停止。2.1.1获取Stream获取数组和集合的Stream获取集合流//集合中Collection的默认方法,1.8后默认添加该方法Streamstream()publicclassStreamDemo1{publicstaticvoidmain(String[]args){ArrayListlist=newArrayList<>();HashSetset=newHashSet<>();HashMapmap=newHashMap<>();//获取集合StreamStreamstream=list.stream();Streamstream1=set.stream();流<对象>stream2=map.keySet().stream();Streamstream3=map.values().stream();}}获取数组流publicclassStreamDemo2{publicstaticvoidmain(String[]args){String[]str={"张三","李四","王二"};//获取数组流Streamstream1=Arrays.stream(str);Streamstream2=Stream.of("张三","李四","王二");}}2.1.2中间操作//常用方法//去除流中的重复元素Streamdistinct()//获取流前指定元素Streamlimit(longmaxSize)//跳过指定元素Streamskip(longn)//过滤流指定数据Streamfilter(Predicatepredicate)//合并两个流staticStreamconcat(Streama,Streamb)//对流处理Streammap(Functionmapper)//示例publicclassStreamDemo3{publicstaticvoidmain(String[]args){//创建数组Integer[]x={0,1,3,5,7,9,11},y={9,2,4,6,8};//创建数组流Streamx1=Stream.of(x);Streamy1=Stream.of(y);Streamconcat=Stream.concat(x1,y1);//跳过前4,取前6,过滤大于等于5的值,去重后结果值乘以10,然后打印流内容结束concat.skip(4).limit(6).filter(i->i>=5).distinct().map(i->i*10).forEach(i->System.out.println(i));}}上述方法是一个非终端方法,操作流后不会关闭。支持链式编程。Collection或者array数据在Stream流中是不能修改的,但是可以通过类似map的方法进行处理。2.1.3可以通过final方法终端方法终止流的运行,非终端方法可以继续链式运行,final方法不支持//普通方法//循环流元素voidforEach(Consumeraction)//统计flowsizelongcount()2.1.4流数据的收集经过一些操作之后,需要获取流中的数据,并转化为集合或者数组。//常用方法//转为arrayA[]toArray(IntFunctiongenerator)//转为collectionRcollect(Collectorcollector)publicclassStreamDemo3{publicstaticvoidmain(String[]args){//创建数组Integer[]x={0,1,3,5,7,9,11,9,2,4,6,8};//获取流Streamstream=Arrays.stream(x);//将流转换为List集合Listlist=stream.filter(i->i>=5).collect(Collectors.toList());//Stream转换为Set集合Setset=stream.collect(Collectors.toSet());//Stream被转换为数组Integer[]array=stream.toArray(value->newInteger[0]);}}3。异常异常是程序在“执行”或“编译”阶段发生的问题,例如越界和空指针问题。一旦出现异常,jvm就会退出执行,所有的异常都必须提前处理,以增加程序的健壮性和安全性。3.1异常系统异常系统主要有:Error:系统级异常,代码乱序控制Excrption:RuntimeException及其子类:运行时异常,未编译。除了以上异常:编译过程中的异常,必须处理,否则程序会编译失败,无法运行。程序写在后缀为java的文件中->使用javac命令将文件编译成类(如果有编译异常则不会通过)->使用java命令运行字节码文件(如果程序有运行时异常,程序会终止程序并报错)->运行结束3.2异常处理3.2.1系统默认的handler会在异常发生的地方默认创建一个异常对象:ArithmeticExceptionfrom异常发生的地方异常发生抛异常给调用者,调用者抛给jvm虚拟机。虚拟机收到异常后,会在控制台显示异常信息。从异常发生的地方终止程序。这种处理是被动的。程序结束。3.2.2手动处理3.2.2.1throws该方法是向调用者抛出可能的异常//格式1修饰返回值方法(形参列表)throws异常类名{}//格式2throw新的异常类名(实参);3.2.2.1try...catch...该方法用于捕获可能出现的异常,如果出现异常,程序员可以自行处理。//格式一try{...}catch(异常类变量名){...}//格式二try{...}catch(异常类变量名1){...}catch(异常类变量nameName2){...}//format2try{...}catch(异常类变量名1){...}finally{...}publicclassTrcatchTest{publicstaticvoidmain(String[]args){尝试{intx=1/0;}catch(Exceptione){//获取异常信息System.out.println("Exceptioninformation:"+e.getMessage());//处理异常代码}System.out.println("继续下一步操作...");}}publicclassTrcatchTest1{publicstaticvoidmain(String[]args){try{intx=1/0;}catch(Exceptione){//获取异常信息System.out.println("异常信息:"+e.getMessage());//处理异常代码}finally{System.out.println("Thisprogramwillalwaysbeexecuted");}System.out.println("继续下面的操作...");}}3.2.2.2混双可以自己抛异常,然后自己捕获异常。这允许集中处理异常。//示例publicclassTrcatchTest2{publicstaticvoidmain(String[]args){try{exceptionTest();}catch(Exceptione){//下面是默认的异常处理方法//e.printStackTrace();系统。out.println(e.getMessage());}}//抛出异常publicstaticvoidexceptionTest()throwsException{//假装有异常thrownewException("Anexceptionoccurred");}}3.3自定义异常程序不可能创建所有的异常,所以我们需要单独创建异常。在这种情况下,会发生异常。既然是自定义异常,所有的异常都处理的比较好。3.3.1自定义编译时异常继承Exceptionrewriteconstructorinplaceofexceptionthrownewexceptionclass(actualparameter)//examplepublicclassExceptioTestextendsException{publicExceptioTest(){}publicExceptioTest(Stringmessage){super(message);}}publicclassTrcatchTest3{publicstaticvoidmain(String[]args){try{exceptionTest();}catch(Exceptione){//下面是默认的异常处理方法//e.printStackTrace();System.out.println(e.getMessage());}}publicstaticvoidexceptionTest()throwsException{//假装有异常thrownewExceptionTest("Anexceptionoccurred");}}3.3.2自定义运行时异常继承RuntimeExceptionoverrideconstructorthrownewexceptionclass(实参)publicclassRuntimeExceptionTestextendsRuntimeException{publicRuntimeExceptionTest(){}publicRuntimeExceptionTest(Stringmessage){super(message);}}publicclassTrcatchTest3{publicstaticvoidmain(String[]args){try{exceptionTest();}catch(Exceptione){//下面是默认的异常处理方法//e.printStackTrace();System.out.println(e.getMessage());}}publicstaticvoidexceptionTest()throwsException{//假装有异常thrownewExceptionTest("Anexceptionoccurred");}}本章到此结束,供个人学习和小白入门使用,勿喷!希望大家喜欢、收藏、支持、支持!源码【GitHub】【码云】