当前位置: 首页 > news >正文

自己总结优化代码写法

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<Student> optionalStudent = list.stream().filter((e) -> e.getStar().equals("天秤座")).findAny();Student student = optionalStudent.get();//4.map 转换集合List<String> names = list.stream().map(Student::getName).collect(Collectors.toList());names.stream().forEach(System.out::println);Map<String, Object> map = new HashMap<>();map.put("key1","1");map.put("key2","1");map.put("key3","1");map.put("key4","1");List<String> cidList = map.keySet().stream().map(String::toString).collect(Collectors.toList()); System.out.println(cidList);//5.mapToInt 转换数值流IntStream intStream = list.stream().mapToInt(Student::getAge);Stream<Integer> integerStream = intStream.boxed();Optional<Integer> max   = integerStream.max(Integer::compareTo);System.out.println(max.get());//6.flatMap 合并成一个流List<String> 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<RedPacketRecord> 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> student = list.stream().findAny();System.out.println(student.get());//15、findFirstOptional<Student> student = list.stream().findFirst();System.out.println(student.get());//17、count 计数long count = list.stream().count();System.out.println(count);//18、ofStream<String> stringStream = Stream.of("i","love","you");//19、emptyStream<String> stringStream2 = Stream.empty();//20、iterateList<String> 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<Student, ?, Double> 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<Integer,List<Student>> 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<Integer,Long> num = list.stream().collect(Collectors.groupingBy(Student::getAge,Collectors.counting()));System.out.println(num);//26、collect:groupingBy(Function, Supplier, Collector)// 先分组,在计算每组的个数,然后排序Map<Integer,Long> 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;
}
http://www.lryc.cn/news/2648.html

相关文章:

  • Java体系最强干货分享—挑战40天准备Java面试,最快拿到offer!
  • 云计算|OpenStack|错误记录和解决方案(不定时更新)
  • 项目实战-NewFixedThreadPool线程池
  • 导数与微分总复习——“高等数学”
  • Linux软件安装
  • 【表面缺陷检测】基于YOLOX的PCB表面缺陷检测(全网最详细的YOLOX保姆级教程)
  • 【C#基础】C# 程序基础语法解析
  • 【webpack】webpack 中的插件安装与使用
  • 生物素-磺基-活性酯,Sulfo-NHS Biotin科研用试剂简介;CAS:119616-38-5
  • Debain安装命令
  • 2023-02-10 - 6 聚合
  • Servlet实现表白墙
  • [python入门㊸] - python测试函数
  • 通讯录文件操作化
  • 为什么 Web3 社交将超越其 Web2 同行
  • 当资深程序员深夜去“打劫”会发生什么?——打家劫舍详解
  • linux 线程
  • Windows 安装appium环境
  • 为什么要在电子产品中使用光耦合器?
  • Vue3 如何实现一个函数式右键菜单(ContextMenus)
  • ffmpeg转码转封装小工具开发
  • 重入和线程安全
  • MySQL数据库06——条件查询(WHERE)
  • Lesson 6.5 机器学习调参基础理论与网格搜索
  • leetcode: Two Sum
  • 共享模型之无锁(三)
  • 微信小程序 Springboot校运会高校运动会管理系统
  • 走进独自开,带你轻松干副业
  • SpringBoot+Vue实现师生健康信息管理系统
  • 数据库第四章节第三次作业内容