Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate string arrays in Java

Tags:

java

arrays

I'm wondering how I can concatenate 4 string arrays in Java.

There is a question about this already. How can I concatenate two arrays in Java?

But I tried to replicate it but it does not work for me.

This is what my code looks like:

Calling the method:

concatAll(jobs1, jobs2, jobs3, jobs4);

The method itself:

public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) {
    int totalLength = jobsA.length;
    for (String[] array : jobsD) {
        totalLength += array.length;
    }

    String[] result = Arrays.copyOf(jobsA, totalLength);

    int offset = jobsA.length;

    for (String[] array : jobsD) {
        System.arraycopy(array, 0, result, offset, array.length);
        offset += array.length;
    }
    return result;
}
like image 386
Tríona Lounds Avatar asked Nov 17 '12 23:11

Tríona Lounds


2 Answers

Putting aside things like checking if an array is null, you can create a general method for it and use it in your specific case, like this:

    public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) 
    {
        return generalConcatAll (jobsA, jobsB, jobsC, jobsD);
    }

    public String[] generalConcatAll(String[]... jobs) {
        int len = 0;
        for (final String[] job : jobs) {
            len += job.length;
        }

        final String[] result = new String[len];

        int currentPos = 0;
        for (final String[] job : jobs) {
            System.arraycopy(job, 0, result, currentPos, job.length);
            currentPos += job.length;
        }

        return result;
    }
like image 78
ShyJ Avatar answered Sep 20 '22 09:09

ShyJ


This is a bit more concise, and handles all null cases correctly using Apache Commons Lang library. ArrayUtils.addAll(T[], T...)

public String[] generalConcatAll(String[]...arrays) {

    String[] result = null;

    for(String[] array : arrays) {
         result = ArrayUtils.addAll(result, array);
    }

    return result;

}
like image 40
yoni Avatar answered Sep 18 '22 09:09

yoni