Close

Java - How to add new elements to arrays?

Java 

This example appends varargs with new array elements on the fly. The method concatMsg concatenates two arrays of any sizes using java.util.stream.Stream#concat(..)


package com.logicbig.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class ConcatArrayTest {

public static void main (String[] args) {
errorMsg("one", "two", "three");
}

public static void errorMsg (String... s) {
String[] newStrings = {"ERROR!!!"};
String[] strings = concat(newStrings, s);
Arrays.stream(strings).forEach(System.out::println);
}

/**
* This method concatenates two string arrays using Stream.concat(..)
*/
public static String[] concat (String[] array1, String[] array2) {
return Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
.toArray(String[]::new);
}
}

Output

ERROR!!!
one
two
three




See Also