- How to join arrays in Java
- Time for an Example:
- Time for another Example:
- In Java how to join Arrays? 3 ways: Apache Commons ArrayUtils, Java 8 Streams and Simple APIs
- Let’s get started:
- java.lang.System.arraycopy():
- java.util.Arrays.toString():
- java.util.stream():
- IntelliJ IDEA console output:
- How to join array in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Code Destine
- Java 8 Array Join – How to join arrays in java using stream API
- Java 8 Array Join
- Problem Statement
- Result :-
- References :-
How to join arrays in Java
In this post, we are going to learn to join multiple arrays into a single array using the Java code. There can be a scenario when we need to combine data of two or more arrays into a single array such as combining two sources into one to transport the data as a single source.
Here, we are using Java 8 stream API to joins arrays and get a result as an array or stream. See the given examples here.
Time for an Example:
Let’s take an example to join two string arrays into a single string array. Here, we are using of() method of Stream that returns a sequence of stream which further is converted into array by using the toArray() method.
import java.util.stream.Stream; public class Main < public static void main(String[] args)< String[] asia = new String[]; String[] europe = new String[]; //join arrays String[] countries = Stream.of(asia,europe).flatMap(Stream::of).toArray(String[]::new); for (String country : countries) < System.out.println(country); >> >
India
Russia
Japan
Poland
Germany
France
Time for another Example:
We can combine two streams by using the concat() method that returns a stream of specified type. The example explains how we can concat two or more stream into a single stream as we did in the above example to combine two arrays.
import java.util.stream.Stream; public class Main < public static void main(String[] args)< Streamstream1 = Stream.of(1, 2, 3); Stream stream2 = Stream.of(4, 5, 6); //concat arrays Stream result = Stream.concat(stream1, stream2); result.forEach(System.out::println); > >
In Java how to join Arrays? 3 ways: Apache Commons ArrayUtils, Java 8 Streams and Simple APIs
In this tutorial we will go over different ways we can join Java Arrays.
If you have any of below questions then you are at right place:
- How can I concatenate two arrays in Java?
- How to Merge Two Arrays in Java?
- 3 Ways to Combine Arrays in Java
- Join Array of Primitives with Separator in Java
Here are the three ways you could you could join arrays in Java.
- Join Array using Apache Common utility
- Join Array using Java8 Stream operation
- Join Array using Standard Java APIs
Let’s get started:
Create java class CrunchifyJoinArrays3Ways.java .
package crunchify.com.tutorial; import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Array; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author Crunchify.com ** In Java how to join Arrays? 3 ways: Apache Commons ArrayUtils, Java 8 Streams and Simple APIs. * Version: 1.0.3 */ public class CrunchifyJoinArrays3Ways < public static void main(String[] args) < crunchifyPrint("Original String Array1: [google, twitter]"); crunchifyPrint("Original String Array2: [apple, microsoft]"); crunchifyPrint("Original Integer Array1: [111, 444]"); crunchifyPrint("Original Integer Array2: [222, 555]\n"); // Join Array using Apache Common utility joinArrayUsingApacheCommon(); // Join Array using Java8 Stream operation joinArrayUsingJava8Stream(); // Join Array using Standard Java APIs joinArrayUsingJavaAPI(); >// Method-1: Join Array using Apache Common utility private static void joinArrayUsingApacheCommon() < String[] company1 = new String[]; String[] company2 = new String[]; // from org.apache.commons.lang3 maven dependency String[] crunchifyResult = ArrayUtils.addAll(company1, company2); crunchifyPrint("From Method-1: addAll() - String ==> " + Arrays.toString(crunchifyResult)); int[] crunchifyArray1 = new int[]; int[] crunchifyArray2 = new int[]; int[] crunchifyResult2 = ArrayUtils.addAll(crunchifyArray1, crunchifyArray2); crunchifyPrint("From Method-1: addAll() - Integer ==> " + Arrays.toString(crunchifyResult2)); > // Simple Java Print Method private static void crunchifyPrint(String result) < System.out.println(result); >// Method-2: Join Array using Java8 Stream operation private static void joinArrayUsingJava8Stream() < String[] company1 = new String[]; String[] company2 = new String[]; // Stream.of() - returns a sequential ordered stream whose elements are the specified values. // A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream: // // int sum = widgets.stream() // .filter(w -> w.getColor() == RED) // .mapToInt(w -> w.getWeight()) // .sum(); String[] result = Stream.of(company1, company2).flatMap(Stream::of).toArray(String[]::new); crunchifyPrint("\nFrom Method-2: Stream.of() ==> " + Arrays.toString(result)); int[] crunchifyArray1 = new int[]; int[] crunchifyArray2 = new int[]; // Arrays.stream() - returns a sequential IntStream with the specified array as its source. int[] crunchifyResult2 = IntStream.concat(Arrays.stream(crunchifyArray1), Arrays.stream(crunchifyArray2)).toArray(); crunchifyPrint("From Method-2: IntStream.concat() ==> " + Arrays.toString(crunchifyResult2)); > // Method-3: Join Array using Standard Java APIs private static void joinArrayUsingJavaAPI() < String[] company1 = new String[]; String[] company2 = new String[]; String[] crunchifyResult = crunchifyJoinGenericArray(company1, company2); crunchifyPrint("\nFrom Method-3: crunchifyJoinArrayusingGeneric() ==> " + Arrays.toString(crunchifyResult)); int[] crunchifyArray1 = new int[]; int[] crunchifyArray2 = new int[]; int[] crunchifyResult2 = crunchifyJoinIntegerArray(crunchifyArray1, crunchifyArray2); // Arrays.toString() Returns a string representation of the contents of the specified array. // The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). // Adjacent elements are separated by the characters ", " (a comma followed by a space). // Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null. crunchifyPrint("From Method-3: joinArray() ==> " + Arrays.toString(crunchifyResult2)); > @SafeVarargs private static T[] crunchifyJoinGenericArray(T[]. crunchifyArrays) < int crunchify = 0; for (T[] crunchifyArray : crunchifyArrays) < crunchify += crunchifyArray.length; >//T[] result = new T[crunchify]; final T[] crunchifyResult = (T[]) Array.newInstance(crunchifyArrays[0].getClass().getComponentType(), crunchify); int crunchifyOffset = 0; for (T[] crunchifyArray : crunchifyArrays) < // Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. // A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. // The number of components copied is equal to the length argument. // The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array. System.arraycopy(crunchifyArray, 0, crunchifyResult, crunchifyOffset, crunchifyArray.length); crunchifyOffset += crunchifyArray.length; >return crunchifyResult; > private static int[] crunchifyJoinIntegerArray(int[]. crunchifyArrays) < int crunchify = 0; for (int[] crunchifyArray : crunchifyArrays) < crunchify += crunchifyArray.length; >final int[] crunchifyResult = new int[crunchify]; int crunchifyOffset = 0; for (int[] crunchifyArray : crunchifyArrays) < System.arraycopy(crunchifyArray, 0, crunchifyResult, crunchifyOffset, crunchifyArray.length); crunchifyOffset += crunchifyArray.length; >return crunchifyResult; > >
Let’s take a look at some of Java API details.
java.lang.System.arraycopy():
java.util.Arrays.toString():
java.util.stream():
Just run program as a Java Program and you should see a result same as below.
IntelliJ IDEA console output:
/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50249:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/app/crunchify/github/CrunchifyTutorials/target/classes:/Users/app/crunchify/github/CrunchifyTutorials/WebContent/WEB-INF/lib/zxing-2.1.jar/Users/app/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar/spring-context-support-5.1.3.RELEASE.jar crunchify.com.tutorial.CrunchifyJoinArrays3Ways Original String Array1: [google, twitter] Original String Array2: [apple, microsoft] Original Integer Array1: [111, 444] Original Integer Array2: [222, 555] From Method-1: addAll() - String ==> [google, twitter, apple, microsoft] From Method-1: addAll() - Integer ==> [111, 444, 222, 555] From Method-2: Stream.of() ==> [google, twitter, apple, microsoft] From Method-2: IntStream.concat() ==> [111, 444, 222, 555] From Method-3: crunchifyJoinArrayusingGeneric() ==> [google, twitter, apple, microsoft] From Method-3: joinArray() ==> [111, 444, 222, 555] Process finished with exit code 0
Please let me know if you have any other way to merge Java Arrays or you get any exception.
If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.
How to join array in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Code Destine
Java 8 Array Join – How to join arrays in java using stream API
4 years ago Lalit Bhagtani 0
Java 8 Array Join
In this tutorial, we will learn about how to join (merge) two or more arrays in Java 8 using Stream API.
Problem Statement
Given an arrays of string data type, merge them together and print all of its values. To implement this, we will use Stream Class of Stream API.
import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; public class MergeArrays < public static void main(String[] args) < String[] s1 = new String[]; String[] s2 = new String[]; String[] s3 = new String[]; /* joining 3 String object type arrays */ String[] result = Stream.concat(Stream.of(s1), Stream.concat(Stream.of(s2), Stream.of(s3))).toArray(String[]::new); System.out.println(Arrays.toString(result)); int[] int1 = new int[]; int[] int2 = new int[]; /* joining 2 int primitive type arrays */ int[] result2 = IntStream.concat(Arrays.stream(int1), Arrays.stream(int2)).toArray(); System.out.println(Arrays.toString(result2)); > >
Result :-
[a, b, c, d, e, f, g, h, i, j, k, l] [1, 2, 3, 4, 5, 6]
References :-
That’s all for how to join (merge) two or more arrays in Java 8 using Stream API. If you liked it, please share your thoughts in comments section and share it with others too.