- 4.7. Java примеры – Как объединить два массива в один
- Результат
- Оглавление
- How to Concatenate Two Arrays in Java
- Как объединить два массива
- Объединения двух массивов с элементами ссылочного типа
- Объединения двух массивов с элементами любого типа
- Объединение массивов с помощью ArrayUtils
- Исходный код
- Заключение
4.7. Java примеры – Как объединить два массива в один
В этом примере показано, как объединить два массива в один массив с помощью метода list.Addall(array1.asList(array2) класса List и метода Arrays.toString() класса Array.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main < public static void main(String args[]) < String a[] = < "А", "Б", "В" >; String b[] = < "Г", "Д" >; List list = new ArrayList(Arrays.asList(a)); list.addAll(Arrays.asList(b)); Object[] c = list.toArray(); System.out.println(Arrays.toString(c)); > >
Результат
Вышеприведенный пример кода даст следующий результат:
Еще один пример соединения массивов в Java.
public class HelloWorld < public static void main(String[] args) < int[]a = ; int[]b = ; int[]c = new int[a.length+b.length]; int count = 0; for(int i = 0; i < a.length; i++) < c[i] = a[i]; count++; >for(int j = 0; j < b.length;j++) < c[count++] = b[j]; >for(int i = 0;i < c.length;i++) System.out.print(c[i]+" "); >>
Вышеприведенный пример кода даст следующий результат:
Оглавление
- 1. Java примеры – Использование кода на практике
- 2. Java примеры – Окружающая среда
- 2.1. Java примеры – Скомпилировать файл
- 2.2. Java примеры – Установить путь к нескольким классам
- 2.3. Java примеры – Отладка java-файла
- 2.4. Java примеры – Установить путь к классу
- 2.5. Java примеры – Просмотреть текущий путь класса
- 2.6. Java примеры – Установить назначение файла класса
- 2.7. Java примеры – Запустить скомпилированный java-файл класса
- 2.8. Java примеры – Узнать версию Java
- 2.9. Java примеры – Установить путь к классу в .jar-файле или .zip-файле
- 3. Java примеры – Строки
- 3.1. Java примеры – Сравнить две строки
- 3.2. Java примеры – Найти последнее вхождение подстроки внутри подстроки
- 3.3. Java примеры – Удалить нужный символ из строки
- 3.4. Java примеры – Заменить символ в строке
- 3.5. Java примеры – Вывод в обратном порядке
- 3.6. Java примеры – Нахождение символа или слова в строке
- 3.7. Java примеры – Разбиение строки на слова и символы
- 3.8. Java примеры – Преобразование строки в верхний регистр
- 3.9. Java примеры – Найти слово в строке
- 3.10. Java примеры – Сравнить производительность создания строки
- 3.11. Java примеры – Оптимизировать создание строк
- 3.12. Java примеры – Форматирование строк
- 3.13. Java примеры – Конкатенация строк
- 3.14. Java примеры – Определить код Юникода символа в строке
- 3.15. Java примеры – Буферизация строк
- 4. Java примеры – Массивы
- 4.1. Java примеры – Сортировка массива и поиск элемента
- 4.2. Java примеры – Метод сортировки массива, вставить элемент в массив
- 4.3. Java примеры – Размер двумерного массива
- 4.4. Java примеры – Обратный порядок массива, переворачиваем массив
- 4.5. Java примеры – Как выводить массивы и двумерные массивы в консоль
- 4.6. Java примеры – Найти максимальный и минимальный элемент массива
- 4.7. Java примеры – Соединить два массива в один
- 4.8. Java примеры – Как заполнить массив числами
- 4.9. Java примеры – Увеличить массив после инициализации
- 4.10. Java примеры – Сравнение двух массивов
- 4.11. Java примеры – Удаление элемента из массива
- 4.12. Java примеры – Удаление массива из другого массива
- 4.13. Java примеры – Одинаковые элементы массивов
- 4.14. Java примеры – Поиск в массиве
- 4.15. Java примеры – Равенство двух массивов
- 4.16. Java примеры – Сравнить массивы
- 5. Java примеры – Дата и время
- 5.1. Java примеры – Форматирование времени в формате AM-PM
- 5.2. Java примеры – Получение названия и номера текущего месяца
- 5.3. Java примеры – Получить текущее время в часах и минутах
- 5.4. Java примеры – Вывести текущее время и дату
- 5.5. Java примеры – Вывести текущее время в 24-часовом формате
- 5.6. Java примеры – Получить текущий месяц
- 5.7. Java примеры – Получить текущие секунды
- 5.8. Java примеры – Получить короткое название месяца
- 5.9. Java примеры – Получить день недели
- 5.10. Java примеры – Добавление времени к дате
- 5.11. Java примеры – Отображение времени в формате другой страны
- 5.12. Java примеры – Отображение времени на разных языках
- 5.13. Java примеры – Прокрутить часы и месяцы
- 5.14. Java примеры – Получить номер недели и месяц в году
- 5.15. Java примеры – Форматы текущей даты
- 6. Java примеры – Методы
- 6.1. Java примеры – Перезагрузка методов
- 6.2. Java примеры – Вывод массива с использованием метода
- 6.3. Java примеры – Решение Ханойской башни
- 6.4. Java примеры – Последовательность чисел Фибоначчи
- 6.5. Java примеры – Вычисление факториала числа
- 6.6. Java примеры – Переопределение метода
- 6.7. Java примеры – Вывод массива с использованием метода
- 6.8. Java примеры – Использование оператора break
- 6.9. Java примеры – Использование оператора continue
- 6.10. Java примеры – Использование метки в методе
- 6.11. Java примеры – Использование операторов enum и switch
- 6.12. Java примеры – Использование конструктора enum
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.
Как объединить два массива
В этой статье мы рассмотрим несколько способов объединения двух массивов. В зависимости от типа элементов (ссылочный или примитивный тип) массива и требований к быстродействию можно применить разные по краткости и удобочитаемости способы.
Объединения двух массивов с элементами ссылочного типа
Данным способом можно объединить массивы ссылочного типа (то есть не массивы с примитивами). Данный способ работает в 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)); > >
Заключение
В этой статье мы рассмотрели различные способы для объединения двух массивов.