Close

Java 11 - Collection Changes

[Last Updated: Sep 28, 2018]

A new default method toArray(IntFunction) has been added to the java.util.Collection interface:

default <T> T[] toArray(IntFunction<T[]> generator)

It returns a new array consisting of the elements of this collection. The provided generator function is used to allocate the returned array.

The new method is an overloaded of the existing toArray(....) methods.

Example

package com.logicbig.example;

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

public class CollectionToArrayExample {
  public static void main(String[] args) {
      List<String> list = List.of("apple", "banana", "orange");
      //old methods
      String[] array = list.toArray(new String[list.size()]);
      System.out.println(Arrays.toString(array));
      Object[] objects = list.toArray();
      System.out.println(Arrays.toString(objects));
      //new method
      String[] array2 = list.toArray(String[]::new);
      System.out.println(Arrays.toString(array2));
  }
}
[apple, banana, orange]
[apple, banana, orange]
[apple, banana, orange]

Example Project

Dependencies and Technologies Used:

  • JDK 9.0.1
java.util.Collection changes Select All Download
  • collection-changes
    • src
      • com
        • logicbig
          • example
            • CollectionToArrayExample.java

    See Also