Java 11 – Collections to Array

Java 11 - Collections to Array

This topic is about Java 11 – Collections to Array.

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;

public class APITester {
   public static void main(String[] args) {		
      List<String> namesList = Arrays.asList("Joe", "Julie");
      // 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

In this topic we learned about Java 11 – Collections to Array. To know more, Click Here.

This Post Has 2 Comments

Leave a Reply