New features in JDK common method

JDK8

  • Lambda expressions

  • Functional Interface

    • Supplier<T>
    • Consumer<T>
    • Function<T, R>
    • Predicate<T>
  • Method references

    • References to members of the object name :: method
    • :: the class name to reference a static method
    • :: the class name references an instance method
    • Class name :: new constructor references
  • Stream flow

More than a few main characteristics in order to better support functional programming

  • Optional classes: In order to solve return null

  • Interface default and static methods

    • default method(default void inf(){})
    • static method (static void inf(){})
  • Date and Time API

    • Date and time classes: LocalDate, LocalTime, LocalDateTime
    • Date and time classes (including time zone): ZonedDate, ZonedTime, ZonedDateTime
    • Time formatting and parsing: DateTimeFormatter
    • Timestamp / Timeline: Instant
    • Date Time difference categories: Duration (for LocalTime), Period (for the LocalDate)
    • Time Correction: TemporalAdjuster (TemporalAdjusters provides an implementation of the common TemporalAdjuster)
  • Repeat annotation and type annotations

    • Repeat Notes: @Repeatable
    • Type Notes: @Target yuan notes there are two new types (TYPE_PARAMETER, TYPE_USE)

JDK9

  • Modular

    module moduleA {
     //导出包
      exports com.test.utils;
      //导入模块
      requires modleB;
    }
    
  • Interactive programming: jshell tool

  • Multi-version used along jar

  • Interface private methods: static methods and interfaces for extracting private methods public methods

  • Release resources code optimization

    FileInputStream fileInputStream = new FileInputStream("F:/a.txt");
    try(fileInputStream){
    	//TODO 操作fileInputStream流 完成后自动关闭
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  • Identifier Optimization: do not allow the use of a separate "_"

  • Change String, StringBuffer, StringBuilder underlying structure: maintaining a character array internal changes to maintain a byte array.

  • Collection of factory methods: quickly create a read-only collection (List.of () ...)

  • The new method Stream stream

    • takeWhile()
    • dropWhile()
    • ofNullable(null)
  • The new HTTPClinet

    import jdk.incubator.http.HttpClient;
    import jdk.incubator.http.HttpRequest;
    import jdk.incubator.http.HttpResponse;
    import java.net.URI;
    import java.net.URISyntaxException;
    
    public class HttpClientDemo {
      public static void main(String[] args) throws Exception {
        //创建HttpClient的对象
        HttpClient httpClient = HttpClient.newHttpClient();
        //创建请求的构造器
        HttpRequest.Builder builder = HttpRequest.newBuilder(new URI("http://www.baidu.com"));
        //使用请求构造器构建请求,并且设置请求的参数
        HttpRequest request = builder.header("user-agent", "hi").GET().build();
        //使用HttpClient发送请求,并且得到响应的对象
        HttpResponse<String> response = httpClient.send(request,HttpResponse.BodyHandler.asString());
        //查看响应对象的信息
        System.out.println("响应状态码:"+ response.statusCode());
        System.out.println("响应的信息:"+response.body());
    }
    

JDK10

  • Delete javah tools: Use the javac -h . 文件名.javagenerated .h file

  • Type inference local variables: variables defined using var

  • New collection method

    • copyof (): returns the set of immutable
  • InputStream & Reader new method

    • transferTo (): byte stream input and the input character stream Reader InputStream added transferTo, can be input data stream to the output stream file copied easily.
  • IO streams large family of new methods

    • The method of adding the parameters Charset: Charset can specify text encoding operation (Charset is an abstract class, with Charset.forName ( "code"), returns the instance of a subclass of Charset)
  • ByteArrayOutputStream new method

    • toString (): the array of data bytes in turn into the memory stream according to the specified code string

JDK11

  • Run directly .java file: not compiled into .class files directly run java filejava 文件名.java

  • Optional new method

    • stream()
    • or()
    • orElseThrow()
    • ofNullable(null)
  • New method string

    • isBlank (): determines whether the string is empty
    • strip (): removing a blank end to end (improved version trim trim only remove the blank 32 ascii code)
    • stripTrailing (): remove trailing spaces
    • stripLeading (): the removal of the head space
    • repeat (3): Copy String
    • lines (): returns Stream <String>, wrapping automatically identify each row and the elementary stream into a String

JDK12

  • switch expression (Preview)

    public static void main(String[] args) {
        Week day = Week.FRIDAY;
        int numLetters = switch (day) {
          case MONDAY, FRIDAY, SUNDAY -> 6;
          case TUESDAY -> 7;
          case THURSDAY, SATURDAY -> 8;
          case WEDNESDAY -> 9;
          default -> throw new IllegalStateException("What day is today?" + day);
       };
     }
    
  • Support compressed digital format: NumberFormat adding support for formatting in a compact digital form. Compact digital format refers to short digital representation or a human-readable form. For example, in the en_US locale, 1000 may be formatted as "1K", 1000000 can be formatted as "1M", depending on the specified style NumberFormat.Style.

    @Test
    public void testCompactNumberFormat(){
    	  var cnf = NumberFormat.getCompactNumberInstance(Locale.CHINA,NumberFormat.Style.SHORT);
    	  System.out.println(cnf.format(1_0000)); //1万
    	  System.out.println(cnf.format(1_9200)); //2万
    	  System.out.println(cnf.format(1_000_000)); //11亿
    	  System.out.println(cnf.format(1L << 30)); //1万
    	  System.out.println(cnf.format(1L << 40)); //1兆
    }
    
  • String new method

    • transform (Function): it provides a function provided as input to a particular String instance, and returns the output of the function returns
    • indent (int): String This method allows us to adjust instance indent
  • Files new method

    • mismatch (Path, Path): compare two files are the same path (eg: Files.mismatch (Path.of ( "tmp / a.txt"), Path.of ( "tmp / b.txt"))
  • Collectors new method

    • teeing (Stream, Stream): a polymerization results downstream of the two

JDK13

  • switch expression (Preview):

    String x = "3";
        int i = switch (x) {
          case "1":
            yield 1;
          case "2":
            yield 2;
          default:
            yield 3;
       };
    System.out.println(i);
    

    Switch 12 is introduced in the JDK expression as a preview feature. JDK 13 offers a second switch expression preview. JEP 354 modifies this feature, it introduces yield statement for the return value. This means, switch expression (return value) should use the yield, switch statements (does not return a value) should use the break.

  • Text block (preview)

    • Original way
    String query = "select employee_id,last_name,salary,department_id\n" +
           "from employees\n" +
           "where department_id in (40,50,60)\n" +
           "order by department_id asc";
    
    • Conventional method (using the "", "text block as a starting symbol and terminator)
    String newQuery = """
       select employee_id,last_name,salary,department_id
       from employees
       where department_id in (40,50,60)
       order by department_id asc
    """;
    
Published 109 original articles · won praise 47 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43934607/article/details/104186151