• JDK 9 开发新特性


    JDK 9 开发新特性

    集合工厂方法

    List,Set 和 Map 接口中,新的工厂方法JEP269可以创建这些集合的不可变实例,代码便得更容易阅读,包括Collection下的List/Set, Map

            // JAVA8 写法
            List<String> list = new ArrayList<>();
            list.add("A");
            list.add("B");
            list.add("C");
            list = Collections.unmodifiableList(list);
            System.out.println(list);
    
            // JAVA9 写法
            List<String> list9 = List.of("A", "B", "C");
            System.out.println(list9);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Optional 增强

    java8中引进的Optional类用来减少程序空指针异常,并使得Stream API更鲁棒。jdk9中为Optional增加了新方法

    • ifPresent(Consumer action): 如果值存在, 执行action表达式,否则什么也不做
    ifPresent(Consumer<? super T> action)
    
    • 1
            // ifPresent(Consumer action)
            Consumer<String> action = (value)-> System.out.println(value) ;
            Optional<String> optionalH = Optional.of("hello word");
            optionalH.ifPresent(action);
    
    • 1
    • 2
    • 3
    • 4
    • ifPresentOrElse(Consumer action, Runnable emptyAction): 和ifPresent相似,有值执行action,没有值执行emptyAction
            // ifPresentOrElse(Consumer action, Runnable emptyAction)
            Optional<String> optionalE =Optional.empty();
            Runnable emptyRun = ()-> System.out.println("空值,默认内容");
            optionalE.ifPresentOrElse(action, emptyRun);
    
    • 1
    • 2
    • 3
    • 4
    • or(Supplier supplier): 如果值存在,返回 Optional 指定的值,否则返回一个预设的值。
            Optional<String> optional1 = Optional.of("Andy");
            Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
            optional1 = optional1.or( supplierString);
            optional1.ifPresent( x -> System.out.println("Value: " + x));
            optional1 = Optional.empty();
            optional1 = optional1.or( supplierString);
            optional1.ifPresent( x -> System.out.println("Value: " + x));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • stream(): 将 Optional 转为一个 Stream,如果该 Optional 中包含值,那么就返回包含这个值的 Stream,否则返回一个空的 Stream(Stream.empty())。(这个功能太棒了!)
    public Stream<T> stream()
    
    • 1
            // java 8
            List<Optional<String>> list = Arrays.asList (
                    Optional.empty(),
                    Optional.of("A"),
                    Optional.empty(),
                    Optional.of("B"));
    
            List<String> filteredList = list.stream()
                    .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
                    .collect(Collectors.toList());
    
            // java 9
            List<String> filteredListJava9 = list.stream()
                    .flatMap(Optional::stream)
                    .collect(Collectors.toList());
    
            System.out.println(filteredList);
            System.out.println(filteredListJava9);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Stream API 增强

    Java 9 改进的 Stream API 添加了一些便利的方法,使流处理更容易,并使用收集器编写复杂的查询

    takeWhile(Predicate)

    有序返回流中的尽可能多的元素,直到断言不为真。

    default Stream<T> takeWhile(Predicate<? super T> predicate)
    
    • 1
            // takeWhile 方法
            Stream.of("1","2","3","","4","5")
                    .takeWhile(s->!s.isEmpty())
                    .forEach(System.out::println);
        	// 打印结果 123
    
    • 1
    • 2
    • 3
    • 4
    • 5

    dropWhile(Predicate)

    default Stream<T> dropWhile(Predicate<? super T> predicate)
    
    • 1

    dropWhile 方法和 takeWhile 作用相似,使用一个断言作为参数,直到断言不为真,返回这之后的stream

    		// dropWhile 方法
            Stream.of("a","b","c","","e","f")
                    .dropWhile(s-> !s.isEmpty())
                     .forEach(System.out::println);
            // 打印结果 ef
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ofNullable 方法

    static <T> Stream<T> ofNullable(T t)
    
    • 1

    ofNullable 方法可以预防 NullPointerExceptions 异常, 可以通过检查流来避免 null 值。

    如果指定元素为非 null,则获取一个元素并生成单个元素流,元素为 null 则返回一个空流。

            
    		// ofNullable
    		long count = Stream.ofNullable( "张").count();
            System.out.println(count);
    
            count = Stream.ofNullable(null).count();
            System.out.println(count);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    iterate 方法

    static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
    
    • 1

    方法允许使用初始种子值创建顺序(可能是无限)流,并迭代应用指定的下一个方法。 当指定的 hasNext 的 predicate 返回 false 时,迭代停止

       // iterator
            IntStream.iterate(3, x -> x < 10, x -> x + 3).forEach(System.out::println);
       // 运行结果
    	3
        6
        9
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    私有接口方法

    在 Java 8之前,接口可以有常量变量抽象方法,java8接口引入了默认方法静态方法,Java 9 不仅像 Java 8 一样支持接口默认方法,同时还支持私有方法私有静态方法

    public class InterfacePrivateMethod {
        public static void main(String[] args) {
            Logging.LogMysql logMysql = new Logging.LogMysql();
            logMysql.logInfo("hello private method");
        }
    }
    interface Logging {
        final class LogMysql implements Logging {
    
        }
    
        private void log(String message, String prefix) {
            getConnection();
            System.out.println("Log Message : " + prefix);
            closeConnection();
        }
        private static void getConnection() {
            System.out.println("Open Database connection");
        }
        private static void closeConnection() {
            System.out.println("Close Database connection");
        }
    
        default void logInfo(String message) {
            log(message, "INFO");
        }
        default void logDebug(String message) {
            log(message, "DEBUG");
        }
    }
    // 程序运行结果
    Open Database connection
    Log Message : INFO
    Close Database connection
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    改进的 try-with-resources

    try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。

    所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源

    try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

        public static void main(String[] args) throws IOException {
            System.out.println(readData7("test7"));
            System.out.println(readData9("test9"));
        }
        // java 7
        static String readData7(String message) throws IOException {
            Reader inputString = new StringReader(message);
            BufferedReader br = new BufferedReader(inputString);
            try (BufferedReader br1 = br) {
                return br1.readLine();
            }
        }
        // java9
        static String readData9(String message) throws IOException {
            Reader inputString = new StringReader(message);
            BufferedReader br = new BufferedReader(inputString);
            try (br) {
                return br.readLine();
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    基于CNN-RNN模型的验证码图片识别
    采用connector-c++ 8.0操作数据库
    x210项目重新回顾之十七升级到linux4.19.114 +buildroot2018再讨论
    编译原理复习——语法分析(自顶向下)
    ROS1Noetic在Win11中安装记录
    1068 Find More Coins
    AbstractQueuedSynchronizer之AQS
    java毕业设计商店管理系统源码+lw文档+mybatis+系统+mysql数据库+调试
    window搭建本地mongo数据库并导入数据
    Spring系列:Spring6简介和基本使用
  • 原文地址:https://blog.csdn.net/m0_37540696/article/details/127773787