自己总结优化代码写法

jdk1.7新特性详解

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

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 statement

    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {

      // Enumerate each entry

      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String 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、anyMatch
        boolean isHave = list.stream().anyMatch(student2 -> student2.getAge() == 16);
        System.out.println(isHave);

        //12、allMatch
        boolean isHave2= list.stream().allMatch(student2 -> student2.getAge() == 16);
        System.out.println(isHave2);

        //13、noneMatch
        boolean isHave3 = list.stream().noneMatch(student2 -> student2.getAge() == 16);
        System.out.println(isHave3);

        //14、findAny
        Optional<Student> student = list.stream().findAny();
        System.out.println(student.get());

        //15、findFirst
        Optional<Student> student = list.stream().findFirst();
        System.out.println(student.get());

        //17、count 计数
        long count = list.stream().count();
        System.out.println(count);

        //18、of
        Stream<String> stringStream = Stream.of("i","love","you");

        //19、empty
        Stream<String> stringStream2 = Stream.empty();

        //20、iterate
        List<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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值