2

I'm trying to add multiple String arrays into a single array using apache commons ArrayUtils as below but it's saying unable to convert Serializable array to String array

// assigning strings arrays
String str1[] = {"hello"};
String str2[] = {"test1"};
String str3[] = {"test2"};
String str4[] = {"hello"};
String str5[] = {"test4"};
String str6[] = {"hello"};

//joining string arrays     
String[] allArrays = ArrayUtils.addAll(str1, str2, str3, str4, str5,str6);
2
  • 1
    addAll doesn't take variable number of arrays. It takes two arrays. Commented Jul 24, 2013 at 8:06
  • Its taking but expecting data type as Serializable array instead of String array Commented Jul 24, 2013 at 8:10

4 Answers 4

2

If you want to concatenate multiple Arrays containing multiple values you can do it in one line using Java 8 streams.

String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};
String[] s3 = new String[]{"g", "h", "i"};

//one liner:
String[] result = Stream.of(s1, s2, s3).flatMap(Stream::of).toArray(String[]::new);

This technique was taken from mkyong.com

Sign up to request clarification or add additional context in comments.

Comments

1

You can use ArrayUtils.addAll in two ways:

    String[] arr1 = {"Hello", "Bye"};
    String[] arr2 = {"Good", "Bad"};

    String[] usage1 = ArrayUtils.addAll(arr1, arr2);
    String[] usage2 = ArrayUtils.addAll(arr1, "New item", "Another item");

The first parameter is an array. The second parameter can be either an array or single items to append to first array.

Comments

0

ArrayUtils.addAll(Object[] array1, Object[] array2) takes only two arguments and returns new array contains all of the element of array1 followed by all of the elements array2.

Comments

0

You can use ArrayUtils.addAll() iteratively, but this causes a performance impact since each time a new copy of the array is created.

String[] allArrays = ArrayUtils.addAll(ArrayUtils.addAll(ArrayUtils.addAll(str1, str2), ArrayUtils.addAll(str3, str4)), ArrayUtils.addAll(str5,str6));

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.