user1631306
user1631306

Reputation: 4470

repeat elements of string array in java

I have a String array with 4 elements. I want to extend this String array with the same elements repeated 3 or n times.

For Example, for the array

String[] array = {"a", "b", "c", "d"};

I want to have something like

String[] array = {"a", "b", "c", "d", "a", "b", "c", "d", "a", "b", "c", "d" };

I tried to something as follows:

String[] columnHeaderNamesArray = {"A","b","c","d"};
String[] extendedColumnHeaderNamesArray = new String[columnHeaderNamesArray.length * 3];
            Arrays.fill(extendedColumnHeaderNamesArray, columnHeaderNamesArray);

But I got an ArrayStoreException.

Upvotes: 1

Views: 281

Answers (1)

Mureinik
Mureinik

Reputation: 311163

You can use Collections.nCopies to create several copies of the same array, and then flat map them to a single array:

String[] multiplied =
    Collections.nCopies(4, array)
               .stream()
               .flatMap(Arrays::stream)
               .toArray(String[]::new);

Upvotes: 1

Related Questions