自己总结优化代码写法
创始人
2024-05-25 10:53:35
0

jdk1.7新特性详解

开发期间略知jdk1.7的一些特性,没有真正的一个一个得展开研究,而是需要说明再去查,导致最整个新特性不是特别的清楚,这种情况以后得需要改变了,否则就会变成代码的奴隶。现在正好有时间可以细细的研究研究了。文章主要参照oracle jdk1.7的官方地址:https://docs.oracle.com/javase/7/docs/technotes/guides/language/enhancements.html#javase7

  • jdk17新特性详解
    • 二进制字面量
    • 在数字字面量使用下划线
    • switch可以使用string了
    • 实例创建的类型推断
    • 使用Varargs方法使用不可维护的形式参数时改进了编译器警告和错误
    • try-with-resources 资源的自动管理
    • 捕捉多个异常类型和对重新抛出异常的高级类型检查

try-with-resources 资源的自动管理

try-with-resources 声明是try 一个或多个资源的声明。一个资源作为一个对象在程序结束之后必须关闭它。try-with-resources声明保证每一个资源都会被关闭在声明结束的时候。任何实现了java.lang.AutoCloseable接口或者实现了java.io.Closeable,可以作为一个资源。
下面的例子从文件中读取第一行。用到了BufferedReader得实例去从文件中读取数据。BufferedReader是一个资源,在程序完成之后必须关闭。

static String readFirstLineFromFile(String path) throws IOException {try (BufferedReader br = new BufferedReader(new FileReader(path))) {return br.readLine();}
}

在这个例子中,在try-with-resources语句中声明的资源是BufferedReader。声明语句出现在try关键字后面的括号内。BufferedReaderJava SE 7及更高版本中的类实现了接口java.lang.AutoCloseable。由于BufferedReader实例是在try-with-resource语句中声明的,因此无论try语句是正常还是意外完成(由于方法BufferedReader.readLine抛出IOException),它都将被关闭。

在Java SE 7之前,无论try语句是正常还是意外完成,都可以使用finally块来确保资源已关闭。以下示例使用finally代替try-with-resources语句的块:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {BufferedReader br = new BufferedReader(new FileReader(path));try {return br.readLine();} finally {if (br != null) br.close();}
}

然而,在这个例子中,如果方法readLineclose都抛出异常,方法readFirstLineFromFileWithFinallyBlock则抛出由finally块抛出的异常,由try块排除的异常将会被抑制。相反,在例子readFirstLineFromFile中,如果try块和try-with-resources声明都抛出异常,方法readFirstLineFromFile则抛出由try块抛出的异常,由try-with-resources抛出的异常将会被抑制。

您可以在try-with-resources语句中声明一个或多个资源。以下示例将检索打包在zip文件zipFileName中的文件的名称,并创建一个包含这些文件名称的文本文件:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName)throws java.io.IOException {java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);// Open zip file and create output file with try-with-resources statementtry (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {// Enumerate each entryfor (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {// Get the entry name and write it to the output fileString newLine = System.getProperty("line.separator");String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;writer.write(zipEntryName, 0, zipEntryName.length());}}}

在此示例中,try-with-resources语句包含两个用分号分隔的声明:ZipFile和BufferedWrite。当直接跟随它的代码块正常结束或由于异常而终止时,close这些BufferedWriter和ZipFile对象的方法将按此顺序自动调用。请注意,close资源的方法是按照与创建相反的顺序来调用的。

捕捉多个异常类型和对重新抛出异常的高级类型检查

处理大于一种类型的异常
在JAVA SE 7 以及以后的版本中,一个简单的catch块可以处理大于一种类型的异常。这个功能可以减少代码重复并且减少了对捕获广泛异常的诱惑。
注意下面的例子,每一个catch块都包含重复代码

catch (IOException ex) {logger.log(ex);throw ex;
catch (SQLException ex) {logger.log(ex);throw ex;
}

在Java SE 7以前的版本中,创建一个通用的方法来消除重复的代码是很困难的,因为变量ex有不同的类型。
以下示例在Java SE 7及更高版本中有效,可消除重复的代码:

catch (IOException|SQLException ex) {logger.log(ex);throw ex;
}

该catch子句指定类型的块处理异常的,以及每个异常类型与竖线分割(|)。
注意:如果一个catch块处理多个异常类型,则该catch参数是隐式的final。在这个例子中,这个catch参数ex是final,所以你不能在这个catch块中赋值。
一个catch块处理多个异常编译生成的字节码要比多个catch块且每个只处理一个异常生成的字节码要小的多,并且优化。一个catch块处理多个异常的代码块通过编译器生成的字节码代码不重复,字节码没有对异常处理程序的复制。

JDK8

1、Lambda 演变过程
2、StreamAPI 详解
3、Date

StreamAPI 详解

功能

父类:BasicStream

子类:Stream、IntStream、LongStream、DoubleStream

包含两个类型,中间操作 (intermediate operations) 和结束操作 (terminal operations)

下面是所有方法的属于那一端操作的方法:

        //1.将集合转换成流list.stream();//2.forEach 遍历list.forEach(System.out::println);//3.filter过滤list.stream().filter((e) -> e.getStar().equals("天秤座")).forEach(System.out::println);Optional optionalStudent = list.stream().filter((e) -> e.getStar().equals("天秤座")).findAny();Student student = optionalStudent.get();//4.map 转换集合List names = list.stream().map(Student::getName).collect(Collectors.toList());names.stream().forEach(System.out::println);Map map = new HashMap<>();map.put("key1","1");map.put("key2","1");map.put("key3","1");map.put("key4","1");List cidList = map.keySet().stream().map(String::toString).collect(Collectors.toList()); System.out.println(cidList);//5.mapToInt 转换数值流IntStream intStream = list.stream().mapToInt(Student::getAge);Stream integerStream = intStream.boxed();Optional max   = integerStream.max(Integer::compareTo);System.out.println(max.get());//6.flatMap 合并成一个流List list2 = new ArrayList<>();list2.add("aaa bbb ccc");list2.add("ddd eee fff");list2.add("ggg hhh iii");list2.add("ggg hhh iii");list2 = list2.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).collect(Collectors.toList());System.out.println(list2);//7.distinct 去重list2.stream().distinct().forEach(System.out::println)//复杂去重
//        List newList = records.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RedPacketRecord::getRoomId))), ArrayList::new));//8、sorted 排序//asc排序list.stream().sorted(Comparator.comparingInt(Student::getAge)).forEach(System.out::println);System.out.println("------------------------------------------------------------------");//desc排序list.stream().sorted(Comparator.comparingInt(Student::getAge).reversed()).forEach(System.out::println);//9、skip 跳过前 n 个list.stream().skip(1).forEach(System.out::println);//10、limit 截取前 n 个list.stream().limit(1).forEach(System.out::println);//11、anyMatchboolean isHave = list.stream().anyMatch(student2 -> student2.getAge() == 16);System.out.println(isHave);//12、allMatchboolean isHave2= list.stream().allMatch(student2 -> student2.getAge() == 16);System.out.println(isHave2);//13、noneMatchboolean isHave3 = list.stream().noneMatch(student2 -> student2.getAge() == 16);System.out.println(isHave3);//14、findAnyOptional student = list.stream().findAny();System.out.println(student.get());//15、findFirstOptional student = list.stream().findFirst();System.out.println(student.get());//17、count 计数long count = list.stream().count();System.out.println(count);//18、ofStream stringStream = Stream.of("i","love","you");//19、emptyStream stringStream2 = Stream.empty();//20、iterateList list = Arrays.asList("a", "b", "c", "c", "d", "f", "a");Stream.iterate(0, i -> i + 1).limit(list.size()).forEach(i -> {System.out.println(String.valueOf(i) + list.get(i));});//21、collect:averagingLong// 求年龄平均值Collector studentDoubleCollector = Collectors.averagingLong(Student::getAge);Double average = list.stream().collect(studentDoubleCollector);//22、collect:collectingAndThen// 求年龄平均值String average2 = list.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Student::getAge), a->"哈哈,平均年龄"+a));System.out.println(average2);//23、collect:counting// 求数量Long num = list.stream().collect(Collectors.counting());System.out.println(num);//24、collect: groupingBy(Function)Map> result = list.stream().collect(Collectors.groupingBy(Student::getAge));for (Integer age:result.keySet()){System.out.println(result.get(age));}//25、collect:groupingBy(Function,Collector)// 先分组,在计算每组的个数Map num = list.stream().collect(Collectors.groupingBy(Student::getAge,Collectors.counting()));System.out.println(num);//26、collect:groupingBy(Function, Supplier, Collector)// 先分组,在计算每组的个数,然后排序Map num = list.stream().collect(Collectors.groupingBy(Student::getAge, TreeMap::new,Collectors.counting()));System.out.println(num);//27、collect:groupingByConcurrent
//        同上,不过这个 Concurrent 是并发的,也有 3 个方法,和上面非并发一个效果
//        groupingByConcurrent(Function)
//        groupingByConcurrent(Function, Collector)
//        groupingByConcurrent(Function, Supplier, Collector)//28、collect:joining()// 名字拼接String result3 = list.stream().map(Student::getName).collect(Collectors.joining());System.out.println(result3);//29、collect:joining(str)// 名字拼接,用逗号隔开String result4 = list.stream().map(Student::getName).collect(Collectors.joining(","));System.out.println(result4);//30、collect:joining(str, prefix, suffix)// 名字拼接,包含前缀、后缀String result5 = list.stream().map(Student::getName).collect(Collectors.joining(",","hello","world"));System.out.println(result5);//31、collect:summarizingDouble// 求年龄的最大值、最小值、平均值、综合以及人数DoubleSummaryStatistics result6 = list.stream().collect(Collectors.summarizingDouble(Student::getAge));System.out.println(result6);//32、collect:toCollection
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;/*** @ClassName Student* @Author: c-wangjz02* @Description:*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Student {//名字private String name;//性别private String sex;//薪水private int salary;//年龄private int age;//星座private String star;
}

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...