Java 11新特性

Java Language Changes for Java SE 11

1. Java 11 String API

1.1 repeat()

将字符串内容重复n次。

  @Test
  public void whenRepeatStringTwice_thenGetStringTwice() {
    String output = "Ha ".repeat(2) + "Land";

    assertEquals(output, "Ha Ha Land");
  }

1.2 strip()

删除字符串前后的空白字符。strip()能识别Unicode,trim()不能识别Unicode。

  @Test
  public void whenStripString_thenReturnStringWithoutWhitespaces() {
    assertEquals("\n\t  hello   \u2005".strip(), "hello");
  }
  @Test
  public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
    assertEquals("\n\t  hello   \u2005".trim(), "hello   \u2005");
  }

1.3 isBlank()

判断字符串是否只包含空白字符。

  @Test
  public void whenBlankString_thenReturnTrue() {
    assertTrue("\n\t\u2005  ".isBlank());
  }

1.4 lines()

将字符串分割成多行字符串。返回Stream。

  @Test
  public void whenMultilineString_thenReturnNonEmptyLineCount() {
    String multilineStr = "This is\n \n a multiline\n string.";

    List<String> lines = multilineStr.lines()
        .filter(Predicate.not(String::isBlank))
        .collect(Collectors.toList());

    assertThat(lines).containsExactly("This is", " a multiline", " string.");
  }

2. File

读取文件内容为字符串。写入字符串内容到文件。

  @Test
  public void testReadStringFromFIleAndWriteStringToFile() throws IOException {
    Path tempDir = Path.of("/tmp");
    Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
    String fileContent = Files.readString(filePath);
    assertEquals(fileContent, "Sample text");
  }

3. Collection to an Array

接收一个IntFunction将集合转换为数组。

  @Test
  public void testCollectionToArray() {
    List<String> sampleList = Arrays.asList("Java", "Kotlin");
    String[] sampleArray = sampleList.toArray(String[]::new);
    assertThat(sampleArray).containsExactly("Java", "Kotlin");
  }

4. Predicate.not()

类似于.negate(),但是可以使用方法引用。

  @Test
  public void testNotPredicate() {
    List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
    List<String> withoutBlanks = sampleList.stream()
        .filter(Predicate.not(String::isBlank))
        .collect(Collectors.toList());
    assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
  }

5. Lambad本地变量

用于添加注解。

  @Test
  public void testLocalVariableInLambda() {
    List<String> sampleList = Arrays.asList("Java", "Kotlin");
    String resultString = sampleList.stream()
        .map((@NotNull var x) -> x.toUpperCase())
        .collect(Collectors.joining(", "));
    assertThat(resultString).isEqualTo("JAVA, KOTLIN");
  }

6. HTTP Client

支持HTTP/1.1 和 HTTP/2。

  @Test
  public void testHttpClient() throws IOException, InterruptedException {
    HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .connectTimeout(Duration.ofSeconds(20))
        .build();
    HttpRequest httpRequest = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("http://httpbin.org/get"))
        .build();
    HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
    assertThat(httpResponse.body()).contains("http://httpbin.org/get");
  }

7. Nest Based Access Control

public class MainClass {

  public class NestedClass {
  }
}
  @Test
  public void testNestBasedAccessControl() {
    assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
    assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);

    Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
        .map(Class::getName)
        .collect(Collectors.toSet());
    assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
  }

8. Running Java Files

不需要使用javac编译,直接运行.java文件。

$ java HelloWorld.java
Hello Java 11!