Home > Back-end >  Java 17: String array initialization
Java 17: String array initialization

Time:12-29

In the latest JDK versions we have Map.of() List.of() utililty methods to initialize Map and List am wondering Is there any other utility method available to initialize String Array in Java 17 other than Array.of("a","b").toJavaArray() and new String[]{"a","b"}?

CodePudding user response:

No, there wasn't any new syntax introduced in Java 17 nor any new utility classes.

To initialize a string array, you can still use the array initializer syntax:

final String[] strings = { "a", "b" };

If you really must, you could write an unsafe method yourself, but be aware how it could break your code at runtime:

public final class NewArray {
  public static <T> T[] from(final T... elements) {
    return elements; // unsafe!
  }

  public static void main() {
    final String[] strings = NewArray.from("a", "b");
  }
}

but that is neither shorter nor clearer … (the only benefit would be that it could be used in place of new String[]{"a","b"} to declare an inline-array when passing it to a method – but again: neither shorter nor clearer, yet unsafe)

CodePudding user response:

List#toArray

You can ask a List to create and populate an array from its elements.

List.of( "a" , "b" ).toArray( String[] :: new )

Streams

One more approach would be making a stream from a list, then collecting these elements into an array.

List.of( "a" , "b" ).stream().toArray( String[] :: new )

This would be helpful if you have additional work. For example, filtering for a subset of elements.

List.of( "a" , "b" ).stream().filter( … ).toArray( String[] :: new )
  • Related