1

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.

3
  • Possible duplicate of Repeating the elements of an array Commented Oct 6, 2017 at 17:28
  • 3
    Did you check javadoc of fill? Commented Oct 6, 2017 at 17:29
  • Arrays.fill() doesn't treat you array as actually array, it's considered as object. So, you're trying to fill array of string with object of array, it's not allowed. Commented Oct 6, 2017 at 17:29

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.