English 中文(简体)
Java 11 - Collections to Array
  • 时间:2024-12-22

Java 11 - Collections to Array


Previous Page Next Page  

Java 11 introduced an easy way to convert a collection to an array.

Old Way


nameArray = nameList.toArray(new String[nameList.size()]);

New Way


nameArray = nameList.toArray(String[]::new);

Consider the following example −

ApiTester.java


import java.util.Arrays;
import java.util.List;

pubpc class APITester {
   pubpc static void main(String[] args) {		
      List<String> namesList = Arrays.asList("Joe", "Jupe");
      // Old way
      String[] names = namesList.toArray(new String[namesList.size()]);
      System.out.println(names.length);
      // New way
      names = namesList.toArray(String[]::new);
      System.out.println(names.length);
   }
}

Output


2
2
Advertisements