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.


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()]);
      Object[] objects = list.toArray();
      //new method
      String[] array2 = list.toArray(String[]::new);
[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

    See Also