user9483860
user9483860

Reputation:

Initialize String[] with empty strings

I want to create a String array containing multiple empty strings.

String[] array = {"", "", "", "", ""};

In python we could achieve this simply with this code [""] * 5. Is there something similar for java?

Upvotes: 3

Views: 8567

Answers (6)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

You can use the fill method from the Arrays class.

String[] test = new String[10];
Arrays.fill(test, "");

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56433

Another approach would be to use IntStream.rangeClosed to generate the required amount of strings.

String[] result = IntStream.rangeClosed(1, 5)
                           .mapToObj(i -> "")
                           .toArray(String[]::new);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Nothing syntactic, no.

At an API level, there's Arrays.fill, but sadly it doesn't return the array you pass it, so you can't use it in the initializer, you have to use it after:

String[] array = new String[5];
Arrays.fill(array, "");

You could always roll-your-own static utility method of course.

public static <T> T[] fill(T[] array, T value) {
    Arrays.fill(array, value);
    return array;
}

then

String[] array = YourNiftyUtilities.fill(new String[5], "");

(Obviously, it would probably be dodgy to do that with mutable objects, but it's fine with String.)

Upvotes: 6

Mena
Mena

Reputation: 48404

With Java 8, you have a not-so-concise, yet better-than-repeated-literals idiom:

// will create a String[] with 42 blank Strings
String[] test = Stream
    // generate an infinite stream with a supplier for empty strings
    .generate(() -> "")
    // make the stream finite to a given size
    .limit(42)
    // convert to array with the given generator function to allocate the array
    .toArray(String[]::new);

Upvotes: 2

JDo
JDo

Reputation: 358

You could try cycle:

String[] array = new String[5];
for (int i = 0; i < 5; i++)
    array[i] = "";

Upvotes: 1

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

The closest would be

String[] array = new String[5];
Arrays.fill(array, "");

however it's not strictly the same as the array would first be initialised with null values.

Upvotes: 1

Related Questions