0

I need to have the following declarations:

private static String[] BASE = new String[] { "a", "b", "c" };
private static String[] EXTENDED = BASE + new String[] { "d", "e", "f" };

The first line declares a string array with three (or more) string values. The second line should declare a string array with all the string values from BASE and then add three (or more) string values.

Is this possible? If yes... how?

6 Answers 6

6

If you're using Java 8, it's a simple one-liner:

Given the two arrays of your question like so:

private static String[] BASE = new String[] { "a", "b", "c" };
private static String[] EXTENSION = new String[] { "d", "e", "f" };

The solution would be:

String[] EXTENDED = Stream.concat(Arrays.stream(BASE), Arrays.stream(EXTENSION))
                      .toArray(String[]::new);
Sign up to request clarification or add additional context in comments.

5 Comments

You may want to replace Arrays.stream(EXTENDED) with Stream.of("d", "e", "f"). Another alternative: private static String[] EXTENDED = Stream.of(BASE, new String[] { "d", "e", "f" }).flatMap(Arrays::stream).toArray(String[]::new); although not as short as concat.
@JonSkeet You are correct. Java 8 is still fairly new, and not a lot of people have explored the stream API to it's fullest.
@RobinJonsson: Well even knowing the stream API, I'd say it's not terribly simple. (The C# would be somewhat simpler: BASE.Concat(EXTENDED).ToArray(), but actually this doesn't show what's requested in the question - which is for EXTENDED to be BASE plus some other members... you might want to edit your answer to actually match the question.)
@JonSkeet I'd say it's pretty simple. But that's my opinion after working with it in heavy business logic for about 6 months. Altough, I'm a fast learner ;) I've edited my answer to fit his example and question better. Thanks for the input.
@RobinJonsson: Thanks for the input. I'm actually stuck on Java 7 for this project so I can't use the Streams API. However, since I forgot to mention this I will acknowledge your answer with JonSkeet's comment.
4

Not like that, no. You can use:

private static String[] EXTENDED = new String[BASE.length + 3];

static {
    System.arraycopy(BASE, 0, EXTENDED, 0, BASE.length);
    EXTENDED[BASE.length] = "d";
    EXTENDED[BASE.length + 1] = "e";
    EXTENDED[BASE.length + 2] = "f";
}

Or write a method to concatenate two arrays, then call it with:

private static String[] BASE = new String[] { "a", "b", "c" };
private static String[] EXTENDED =
    ArrayUtils.concat(BASE, new String[] { "d", "e", "f" });

I don't know of such a method in the JRE, but it wouldn't be hard to write - or use the streams API if you want.

Comments

1

There is solution in Apache Commons Lang library: ArrayUtils.addAll(T[], T...)

String[] both = ArrayUtils.addAll(firstArray, secondArray);

1 Comment

Even with the improvements of Java 8 I still use Apache Commons Lang frequently...it's my favorite general purpose library by far. In this particular case the code you've posted is easier to read than the Java 8 one-line solution so I'd go with your solution if performance isn't a consideration.
0

Not relying on Java 8, here's another solution:

String[] BASE = new String[] { "a", "b", "c" };
String[] EXT = new String[] { "d", "e", "f" };

String[] CONCAT = Arrays.copyOf (BASE, BASE.length + EXT.length);
System.arraycopy(EXT, 0, CONCAT, BASE.length, EXT.length);

Comments

0

I put together a JoinedArray class a while ago that could help. It's a bit of overkill if you dont want to do this very often but if you do this a lot in your code you may find it of use.

It does not actually join the arrays into a new one - it actually provides an Iterable that can then iterate across the joined arrays.

public class JoinedArray<T> implements Iterable<T> {
  final List<T[]> joined;

  @SafeVarargs
  public JoinedArray(T[]... arrays) {
    joined = Arrays.<T[]>asList(arrays);
  }

  @Override
  public Iterator<T> iterator() {
    return new JoinedIterator<>(joined);
  }

  private class JoinedIterator<T> implements Iterator<T> {
    // The iterator across the arrays.
    Iterator<T[]> i;
    // The array I am working on.
    T[] a;
    // Where we are in it.
    int ai;
    // The next T to return.
    T next = null;

    private JoinedIterator(List<T[]> joined) {
      i = joined.iterator();
      a = i.hasNext() ? i.next() : null;
      ai = 0;
    }

    @Override
    public boolean hasNext() {
      while (next == null && a != null) {
        // a goes to null at the end of i.
        if (a != null) {
          // End of a?
          if (ai >= a.length) {
            // Yes! Next i.
            if (i.hasNext()) {
              a = i.next();
            } else {
              // Finished.
              a = null;
            }
            ai = 0;
          }
          if (a != null) {
            if (ai < a.length) {
              next = a[ai++];
            }
          }
        }
      }
      return next != null;
    }

    @Override
    public T next() {
      T n = null;
      if (hasNext()) {
        // Give it to them.
        n = next;
        next = null;
      } else {
        // Not there!!
        throw new NoSuchElementException();
      }
      return n;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("Not supported.");
    }

  }

  public static void main(String[] args) {
    JoinedArray<String> a = new JoinedArray<>(
            new String[]{
              "Zero",
              "One"
            },
            new String[]{},
            new String[]{
              "Two",
              "Three",
              "Four",
              "Five"
            },
            new String[]{
              "Six",
              "Seven",
              "Eight",
              "Nine"
            });
    for (String s : a) {
      System.out.println(s);
    }

  }

}

Comments

0
// Create 2 Arrays
String[] first = new String[]{"a","b","c"};
String[] second = new String[]{"d","e","f"};

// Create a List
List<String> tempList = new ArrayList<String>();

// Then add both arrays in the List
tempList.addAll(Arrays.asList(first));
tempList.addAll(Arrays.asList(second));

// Then convert the List into array
String[] finalStr =  tempList.toArray(new String[tempList.size()]);

// Thats it

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.