logo

كيفية دمج مصفوفتين في جافا

يشبه دمج صفيفين في Java سلسلة أو دمج صفيفين في كائن صفيف واحد. يتعين علينا دمج صفيفين بحيث تحافظ عناصر المصفوفة على ترتيبها الأصلي في المصفوفة المدمجة حديثًا. تسبق عناصر المصفوفة الأولى عناصر المصفوفة الثانية في المصفوفة المدمجة حديثًا. على سبيل المثال:

 int[] arr1={1, 2, 3, 4, 5, 6}; //first array int[] arr2={7, 8, 9, 0}; //second array int[] arr3={1, 2, 3, 4, 5, 6, 7, 8, 9, 0} //resultant array 

هناك الطرق التالية لدمج صفيفين:

  • جافا نسخة المصفوفة () طريقة
  • دون استخدام نسخة المصفوفة () طريقة
  • جافا المجموعات
  • جافا تدفق واجهة برمجة التطبيقات

طريقة Java arraycopy ().

جافا نسخة المصفوفة () هي طريقة نظام الطبقة التي تنتمي إليها java.lang طَرد. يقوم بنسخ مصفوفة من المصفوفة المصدر المحددة إلى الموضع المحدد للمصفوفة الوجهة. عدد العناصر المنسوخة يساوي وسيطة الطول.

بناء الجملة:

com.execlp
 public static void arraycopy(Object source, int source_position, Object destination, int destination_position, int length) 

حدود

    مصدر: إنها مجموعة المصدر.source_position: نقطة البداية في المصفوفة المصدر.وجهة: إنها مصفوفة الوجهة.Destination_position: موضع البداية في صفيف الوجهة.طول: عدد عناصر المصفوفة المراد نسخها

يرمي NullPointerException إذا كانت مجموعة المصدر أو الوجهة فارغة. ويرمي أيضا ArrayIndexOutOfBoundsException إذا :

    source_positionأو Destination_position أو الطول سلبيsource_position+lengthأكبر من طول المصفوفة المصدر، أو Destination_position+length أكبر من طول المصفوفة الوجهة.

مثال على طريقة arraycopy()

في المثال التالي، قمنا بإنشاء مصفوفتين صحيحتين firstArray و SecondArray . ومن أجل دمج مصفوفتين، نجد طوله ونخزنه في متغير fal وsal على التوالي. بعد ذلك، نقوم بإنشاء مصفوفة أعداد صحيحة جديدة نتيجة الذي يخزن مجموع طول كلا المصفوفتين. الآن، انسخ كل عنصر من كلا المصفوفتين إلى المصفوفة الناتجة باستخدام نسخة المصفوفة () وظيفة.

 import java.util.Arrays; public class MergeArrayExample1 { public static void main(String[] args) { int[] firstArray = {23,45,12,78,4,90,1}; //source array int[] secondArray = {77,11,45,88,32,56,3}; //destination array int fal = firstArray.length; //determines length of firstArray int sal = secondArray.length; //determines length of secondArray int[] result = new int[fal + sal]; //resultant array of size first array and second array System.arraycopy(firstArray, 0, result, 0, fal); System.arraycopy(secondArray, 0, result, fal, sal); System.out.println(Arrays.toString(result)); //prints the resultant array } } 

انتاج:

 [23, 45, 12, 78, 4, 90, 1, 77, 11, 45, 88, 32, 56, 3] 

دعونا نرى مثالًا آخر حددنا فيه soure_array، والوجهة، وdest_position، وموضع المصدر، والطول. يمكننا دمج المصفوفة وفقًا للمواضع والطول المحددين.

مثال

 import java.lang.*; public class MergeArrayExample2 { public static void main(String[] args) { int firstArray[] = { 11,22,33,44,55,98,76,54,60}; int secondArray[] = {66,77,88,99,22,67,21,90,80,70}; int source_arr[], sourcePos, dest_arr[], destPos, len; source_arr = firstArray; dest_arr = secondArray; sourcePos = 2; destPos = 4; len = 3; // Print elements of source System.out.print(&apos;source_array : &apos;); for (int i = 0; i <firstarray.length; i++) system.out.print(firstarray[i] + ' '); system.out.println(''); system.out.println('sourcepos : sourcepos); print elements of destination system.out.print('dest_array for (int i="0;" < secondarray.length; system.out.print(secondarray[i] system.out.println('destpos destpos); system.out.println('len len); invoking arraycopy() method system.arraycopy(source_arr, sourcepos, dest_arr,destpos, after system.out.print('resultant array } pre> <p> <strong>Output:</strong> </p> <pre> source_array: 11 22 33 44 55 98 76 54 60 sourcePos: 2 dest_array: 66 77 88 99 22 67 21 90 80 70 destPos: 4 len: 3 Resultant array: 66 77 88 99 33 44 55 90 80 70 </pre> <h2>Without using arraycopy() method</h2> <p> <strong>Example of merging two arrays</strong> </p> <p>In the following example, we have initialized two arrays firstArray and secondArray of integer type. Manually copy the each element of both arrays to mergedArray and convert that array into String by using toString() method of Array class.</p> <pre> public class MergeArrayExample3 { public static void main(String[] args) { int[] firstArray = {56,78,90,32,67,12}; //initialized array int[] secondArray = {11,14,9,5,2,23,15}; int length = firstArray.length + secondArray.length; //add the length of firstArray into secondArray int[] mergedArray = new int[length]; //resultant array int pos = 0; for (int element : firstArray) //copying elements of secondArray using for-each loop { mergedArray[pos] = element; pos++; //increases position by 1 } for (int element : secondArray) //copying elements of firstArray using for-each loop { mergedArray[pos] = element; pos++; } System.out.println(Arrays.toString(mergedArray)); //prints the resultant array } } </pre> <p> <strong>Output:</strong> </p> <pre> [56, 78, 90, 32, 67, 12, 11, 14, 9, 5, 2, 23, 15] </pre> <h2>Using Collections</h2> <p> <strong>Example of merging two arrays in Java</strong> </p> <p>In the following example, we have initialized two arrays str1 and str2 of String type. After that we have created a list view of str1 by using the Arrays.asList() method. Now we have created the list view of str2 and added all the elements of str2 into the list. Again perform conversion from list to array and store the resultant array into str3 variable.</p> <pre> import java.util.*; public class MergeArrayExample4 { public static void main(String args[]) { String str1[] = { &apos;A&apos;, &apos;E&apos;, &apos;I&apos; }; //source array String str2[] = { &apos;O&apos;, &apos;U&apos; }; //destination array List list = new ArrayList(Arrays.asList(str1)); //returns a list view of an array //returns a list view of str2 and adds all elements of str2 into list list.addAll(Arrays.asList(str2)); Object[] str3 = list.toArray(); //converting list to array System.out.println(Arrays.toString(str3)); //prints the resultant array } } </pre> <p> <strong>Output:</strong> </p> <pre> [A, E, I, O, U] </pre> <h2>Java Stream API</h2> <p> <strong>Stream.of() method</strong> </p> <p>The <strong>Stream.of()</strong> method of Stream interface returns a sequential ordered stream whose elements are the values.</p> <p> <strong>Syntax</strong> </p> <pre> static Stream of(T....values) </pre> <p>Where M <strong>T</strong> is the type of stream elements. The method accepts <strong>values</strong> (elements of the new stream).</p> <p> <strong>flatMap() method</strong> </p> <p>The <strong>flatMap()</strong> method is the method of Stream interface. It returns a stream consisting of the result.</p> <p> <strong>Syntax</strong> </p> <pre> Stream flatMap(Function<? Super T, ? extends Stream> mapper) </pre> <p>Where <strong>R</strong> is the element type of new stream. The method accepts a <strong>mapper</strong> (a function to apply to each element which produces a stream of new values) as a parameter.</p> <p> <strong>toArray() method</strong> </p> <p>The <strong>toArray()</strong> method of Stream interface returns an array containing the elements of the stream.</p> <p> <strong>Syntax</strong> </p> <pre> Object[] toArray() </pre> <p> <strong>Example of merging two arrays using Stream API</strong> </p> <pre> import java.util.stream.Stream; import java.util.Arrays; import java.io.*; public class MergeArrayExample5 { // function to merge two arrays public static Object[] mergeArray(T[] arr1, T[] arr2) { return Stream.of(arr1, arr2).flatMap(Stream::of).toArray(); } public static void main (String[] args) { Integer[] firstArray = new Integer[]{13,12,11,6,9,3}; //source array Integer[] secondArray = new Integer[]{78,34,56,67,2,11,7}; //destination array Object[] mergedArray = mergeArray(firstArray,secondArray); //merged array System.out.println(&apos;Merged array: &apos;+ Arrays.toString(mergedArray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Merged array: [13, 12, 11, 6, 9, 3, 78, 34, 56, 67, 2, 11, 7] </pre> <hr></firstarray.length;>

بدون استخدام طريقة arraycopy()

مثال على دمج مصفوفتين

إذا كان البيان آخر Java

في المثال التالي، قمنا بتهيئة صفيفين firstArray و SecondArray من النوع الصحيح. انسخ كل عنصر من كلا المصفوفتين يدويًا إلى mergedArray وقم بتحويل هذا المصفوفة إلى سلسلة باستخدام طريقة toString () لفئة Array.

 public class MergeArrayExample3 { public static void main(String[] args) { int[] firstArray = {56,78,90,32,67,12}; //initialized array int[] secondArray = {11,14,9,5,2,23,15}; int length = firstArray.length + secondArray.length; //add the length of firstArray into secondArray int[] mergedArray = new int[length]; //resultant array int pos = 0; for (int element : firstArray) //copying elements of secondArray using for-each loop { mergedArray[pos] = element; pos++; //increases position by 1 } for (int element : secondArray) //copying elements of firstArray using for-each loop { mergedArray[pos] = element; pos++; } System.out.println(Arrays.toString(mergedArray)); //prints the resultant array } } 

انتاج:

 [56, 78, 90, 32, 67, 12, 11, 14, 9, 5, 2, 23, 15] 

استخدام المجموعات

مثال على دمج صفيفين في جافا

في المثال التالي، قمنا بتهيئة صفيفين str1 وstr2 من نوع السلسلة. بعد ذلك قمنا بإنشاء عرض قائمة لـ str1 باستخدام طريقة Arrays.asList(). لقد أنشأنا الآن عرض القائمة لـ str2 وأضفنا جميع عناصر str2 إلى القائمة. قم بإجراء التحويل مرة أخرى من قائمة إلى صفيف وقم بتخزين الصفيف الناتج في متغير str3.

 import java.util.*; public class MergeArrayExample4 { public static void main(String args[]) { String str1[] = { &apos;A&apos;, &apos;E&apos;, &apos;I&apos; }; //source array String str2[] = { &apos;O&apos;, &apos;U&apos; }; //destination array List list = new ArrayList(Arrays.asList(str1)); //returns a list view of an array //returns a list view of str2 and adds all elements of str2 into list list.addAll(Arrays.asList(str2)); Object[] str3 = list.toArray(); //converting list to array System.out.println(Arrays.toString(str3)); //prints the resultant array } } 

انتاج:

كيفية تغيير السلسلة إلى int
 [A, E, I, O, U] 

جافا ستريم API

طريقة Stream.of()

ال تيار() تُرجع طريقة واجهة الدفق دفقًا مرتبًا متسلسلًا تكون عناصره هي القيم.

بناء الجملة

 static Stream of(T....values) 

حيث م ت هو نوع عناصر الدفق. تقبل الطريقة قيم (عناصر التيار الجديد).

طريقة flatMap ().

ال خريطة مسطحة() الطريقة هي طريقة واجهة الدفق. تقوم بإرجاع دفق يتكون من النتيجة.

الصف مقابل العمود

بناء الجملة

 Stream flatMap(Function<? Super T, ? extends Stream> mapper) 

أين ر هو نوع العنصر للتيار الجديد. تقبل الطريقة أ مصمم الخرائط (وظيفة يتم تطبيقها على كل عنصر ينتج دفقًا من القيم الجديدة) كمعلمة.

بريتي زينتا

طريقة toArray()

ال لمجموعة() تقوم طريقة واجهة الدفق بإرجاع مصفوفة تحتوي على عناصر الدفق.

بناء الجملة

 Object[] toArray() 

مثال على دمج صفيفين باستخدام Stream API

 import java.util.stream.Stream; import java.util.Arrays; import java.io.*; public class MergeArrayExample5 { // function to merge two arrays public static Object[] mergeArray(T[] arr1, T[] arr2) { return Stream.of(arr1, arr2).flatMap(Stream::of).toArray(); } public static void main (String[] args) { Integer[] firstArray = new Integer[]{13,12,11,6,9,3}; //source array Integer[] secondArray = new Integer[]{78,34,56,67,2,11,7}; //destination array Object[] mergedArray = mergeArray(firstArray,secondArray); //merged array System.out.println(&apos;Merged array: &apos;+ Arrays.toString(mergedArray)); } } 

انتاج:

 Merged array: [13, 12, 11, 6, 9, 3, 78, 34, 56, 67, 2, 11, 7]