Слить два массива java

Как сложить два массива в java

Чтобы сложить два массива в Java , нужно создать новый массив, который будет содержать элементы из обоих массивов. Например, если у нас есть два массива array1 и array2 , то мы можем создать новый массив resultArray следующим образом:

int[] array1 = 1, 2, 3>; int[] array2 = 4, 5, 6>; int[] resultArray = new int[array1.length + array2.length]; 

Затем мы можем использовать метод System.arraycopy() для копирования элементов из каждого из массивов в новый массив:

System.arraycopy(array1, 0, resultArray, 0, array1.length); System.arraycopy(array2, 0, resultArray, array1.length, array2.length); 

В результате в массив resultArray будут скопированы все элементы из массивов array1 и array2

Источник

Как объединить два массива

В этой статье мы рассмотрим несколько способов объединения двух массивов. В зависимости от типа элементов (ссылочный или примитивный тип) массива и требований к быстродействию можно применить разные по краткости и удобочитаемости способы.

Объединения двух массивов с элементами ссылочного типа

Данным способом можно объединить массивы ссылочного типа (то есть не массивы с примитивами). Данный способ работает в Java 6 и выше.

public static T[] concat(T[] first, T[] second)

Можно воспользоваться возможностями Java 8 и сделать объединение массивов с помощью стримов:

@SuppressWarnings("unchecked") public static T[] concatUsingStream(T[] a, T[] b) < return Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray( size ->(T[]) Array.newInstance(a.getClass().getComponentType(), size)); >

Объединения двух массивов с элементами любого типа

В отличие от предыдущего способа, здесь мы можем объединить массивы не только ссылочного типа, но и примитивного:

public static T concatAny(T a, T b) < if (!a.getClass().isArray() || !b.getClass().isArray()) < throw new IllegalArgumentException(); >Class resCompType; Class aCompType = a.getClass().getComponentType(); Class bCompType = b.getClass().getComponentType(); if (aCompType.isAssignableFrom(bCompType)) < resCompType = aCompType; >else if (bCompType.isAssignableFrom(aCompType)) < resCompType = bCompType; >else < throw new IllegalArgumentException(); >int aLen = Array.getLength(a); int bLen = Array.getLength(b); @SuppressWarnings("unchecked") T result = (T) Array.newInstance(resCompType, aLen + bLen); System.arraycopy(a, 0, result, 0, aLen); System.arraycopy(b, 0, result, aLen, bLen); return result; >

Объединение массивов с помощью ArrayUtils

Наиболее лаконичный способ объединить элементы двух массивов – это воспользоваться классов ArrayUtils из Commons Lang. Для этого сначала нужно подключить библиотеку в проект:

 org.apache.commons commons-lang3 3.9 
String[] a = new String[]; String[] b = new String[]; ArrayUtils.addAll(a, b); // [A, B, C, D, E, F]

Исходный код

import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Array; import java.util.Arrays; import java.util.stream.Stream; public class UnionArraysExample < public static void main(String[] args) < String[] a = new String[]; String[] b = new String[]; int[] c = new int[]; int[] d = new int[]; System.out.println(Arrays.toString(concat(a, b))); System.out.println(Arrays.toString(concatAny(c, d))); System.out.println(Arrays.toString(concatUsingStream(a, b))); System.out.println(Arrays.toString(ArrayUtils.addAll(a, b))); // [A, B, C, D, E, F] > public static T[] concat(T[] first, T[] second) < T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; >public static T concatAny(T a, T b) < if (!a.getClass().isArray() || !b.getClass().isArray()) < throw new IllegalArgumentException(); >Class resCompType; Class aCompType = a.getClass().getComponentType(); Class bCompType = b.getClass().getComponentType(); if (aCompType.isAssignableFrom(bCompType)) < resCompType = aCompType; >else if (bCompType.isAssignableFrom(aCompType)) < resCompType = bCompType; >else < throw new IllegalArgumentException(); >int aLen = Array.getLength(a); int bLen = Array.getLength(b); @SuppressWarnings("unchecked") T result = (T) Array.newInstance(resCompType, aLen + bLen); System.arraycopy(a, 0, result, 0, aLen); System.arraycopy(b, 0, result, aLen, bLen); return result; > @SuppressWarnings("unchecked") public static T[] concatUsingStream(T[] a, T[] b) < return Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray( size ->(T[]) Array.newInstance(a.getClass().getComponentType(), size)); > >

Заключение

В этой статье мы рассмотрели различные способы для объединения двух массивов.

Источник

How to Concatenate Two Arrays in Java

Learn to concatenate two primitive arrays or objects arrays to create a new array consisting of the items from both arrays. We will learn to merge array items using simple for-loop, stream API and other utility classes.

Note that no matter which technique we use for merging the arrays, it always creates a new array of combined length of both arrays and then copies the items from both arrays into the new array, one at a time, in a loop. So the main difference between the various ways, discussed below, is code readability and ease of use.

1. Concatenating Arrays with ‘for loop’

Directly using the for-loop to merge the arrays is the most efficient in terms of performance. It does not create unnecessary temporary variables and objects.

We create a new array of combined length of two given arrays and then start putting items from both arrays into the new array in a loop. Theoretically, this method should give the best performance.

int[] intArray1 = ; int[] intArray2 = ; result = new int[intArray1.length + intArray2.length]; int index = 0; for (int item: intArray1) < result[index++] = item; >for (int item: intArray2) < result[index++] = item; >System.out.println(Arrays.toString(result)); //[1, 2, 3, 4, 5, 6]

Using arraycopy() is equivalent to using the for-loop. Here we delegate the task of copying the array items into a new array to the native function arraycopy() .

Performance-wise, arraycopy() method should perform on par with the for-loop method.

int[] intArray1 = ; int[] intArray2 = ; int[] result = new int[intArray1.length + intArray2.length]; System.arraycopy(intArray1, 0, result, 0, intArray1.length); System.arraycopy(intArray2, 0, result, intArray1.length, intArray2.length); System.out.println(Arrays.toString(result)); //[1, 2, 3, 4, 5, 6]

We can write a generic type method that can be used to merge the arrays holding the items of any object type.

static T[] concatArrays(T[] array1, T[] array2) < T[] result = Arrays.copyOf(array1, array1.length + array2.length); System.arraycopy(array2, 0, result, array1.length, array2.length); return result; >//Invoking the method String[] resultObj = concatArrays(strArray1, strArray2); System.out.println(Arrays.toString(resultObj)); //[1, 2, 3, 4, 5, 6]

3. Merging Arrrays with Stream.concat()

The stream.concat() method creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

To obtain the streams, we convert the arrays into streams and then concat() to merge the streams. Later, we can collect the stream items into an array to complete the merge process.

String[] strArray1 = ; String[] strArray2 = ; String[] both = Stream.concat(Arrays.stream(strArray1), Arrays.stream(strArray2)) .toArray(String[]::new);

We can use this technique to concatenate more than two arrays in a single statement.

String[] mergedArray = Stream.concat(Arrays.stream(strArray1), Arrays.stream(strArray2), Arrays.stream(strArray3), Arrays.stream(strArray4)) .toArray(String[]::new);

To merge the array of primitives, we can directly use the following classes:

These classes provide the concat() methods specific to these primitives.

int[] intArray1 = ; int[] intArray2 = ; int[] result = IntStream.concat(Arrays.stream(intArray1), Arrays.stream(intArray2)) .toArray();

4. ArrayUtils from Apache Commons

We can use the 3rd part libraries that provide easy-to-use one-line methods for merging the arrays. They also provide the same level of performance as previous methods.

A similar API is ArrayUtils.addAll() that adds all the elements of the given arrays into a new array. Note that the returned array always returns a new array, even if we are merging two arrays and one of them is null .

String[] resultObj = ArrayUtils.addAll(strArray1, strArray2); int[] result = ArrayUtils.addAll(intArray1, intArray2);

Guava APIs provide the following classes that we can use to merge arrays of primitives as well as arrays of object types.

  • Ints.concat() : concatenates two int arrays.
  • Longs.concat() : concatenates two long arrays.
  • Doubles.concat() : concatenates two double arrays.
  • ObjectArrays.concat() : concatenates two object type arrays.
String[] resultObj = ObjectArrays.concat(strArray1, strArray2, String.class); int[] result = Ints.concat(intArray1, intArray2);

In this tutorial, we learned to merge two arrays in Java. We learned to use the native Java APIs as well as the utility classes from the 3rd party libraries.

All the above methods will give almost the same level of performance for small arrays. For big arrays, it is recommended to do performance testing before finalizing the approach. However theoretically, using the for-loop and arraycopy() method should provide the best performance among all.

Источник

How to concatenate two arrays in Java

In this short article, you will learn about different ways to concatenate two arrays into one in Java.

int[] arr1 = 1, 2, 3, 4>; int[] arr2 = 5, 6, 7, 8>; // create a new array int[] result = new int[arr1.length + arr2.length]; // add elements to new array int index = 0; for (int elem : arr1)  result[index] = elem; index++; > for (int elem : arr2)  result[index] = elem; index++; > System.out.println(Arrays.toString(result)); 

Another way of concatenating two arrays in Java is by using the System.arraycopy() method (works for both primitive and generic types), as shown below:

int[] arr1 = 1, 2, 3, 4>; int[] arr2 = 5, 6, 7, 8>; // create a new array int[] result = new int[arr1.length + arr2.length]; // concatenate arrays System.arraycopy(arr1, 0, result, 0, arr1.length); System.arraycopy(arr2, 0, result, arr1.length, arr2.length); System.out.println(Arrays.toString(result)); 

If you can using Java 8 or higher, it is also possible to use the Stream API to merge two arrays into one. Here is an example:

String[] arr1 = "a", "b", "c", "d">; String[] arr2 = "e", "f", "g", "h">; // concatenate arrays String[] result = Stream.of(arr1, arr2).flatMap(Stream::of).toArray(String[]::new); System.out.println(Arrays.toString(result)); 
int[] arr1 = 1, 2, 3, 4>; int[] arr2 = 5, 6, 7, 8>; // concatenate arrays int[] result = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).toArray(); System.out.println(Arrays.toString(result)); 

If you are already using the Apache Commons Lang library, just use the ArrayUtils. addAll() method to concatenate two arrays into one. This method works for both primitive as well as generic type arrays.

String[] arr1 = "a", "b", "c", "d">; String[] arr2 = "e", "f", "g", "h">; // concatenate arrays String[] result = ArrayUtils.addAll(arr1, arr2); System.out.println(Arrays.toString(result)); // [a, b, c, d, e, f, g, h] 
int[] arr1 = 1, 2, 3, 4>; int[] arr2 = 5, 6, 7, 8>; // concatenate arrays int[] result = ArrayUtils.addAll(arr1, arr2); System.out.println(Arrays.toString(result)); // [1, 2, 3, 4, 5, 6, 7, 8] 
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency> 
implementation 'org.apache.commons:commons-lang3:3.9' 

You might also like.

Источник

Читайте также:  Как сделать локальную переменную глобальной в питон
Оцените статью