By Wael

Posted :

arrays in java a tutorial

This tutorial is about arrays in java . It will show how to declare and create arrays , how to assign values and access elements of an array , how to loop , and print the elements of an array .

It will also show how to copy , clone and merge arrays . How to sort , search , and check for the equality of arrays . How to fill an array , generate an array , reduce an array : find the max , min or average ... How to convert arrays to streams , or collections , how to reverse an array , and how to calculate the Cartesian product of two arrays .

arrays java tutorial
Table of contents Declaring and Creating arrays Array length Assigning values to elements of an array Accessing the elements of an array Looping through arrays Printing arrays Copying and cloning arrays Merging arrays Sorting arrays Searching for an element in an Array Checking for arrays equality Filling an array Generating an array Finding the max and min elements of an array Finding the average , and the sum of an array Reducing an array Converting arrays Reversing an Array Cartesian product of Two arrays

1- Declaring and Creating arrays

A variable of type array , can be declared by using either Type[] nameOfVariable or Type nameOfVariable[] . In the first case all the variables after Type[] are of type array . In the second case , only the variable with the square brackets is of type array . There can be spaces between Type and [] .

  1. int[] iArrayOne , iArrayTwo ;
  2. /*
  3. iArrayOne and iArrayTwo are variables
  4. of type int[] , since the square brackets
  5. are placed after the int type .*/
  6.  
  7.  
  8. String sArray[] , aString ;
  9. /*
  10. sArray is a variable of type
  11. String[] , since the square
  12. brackets is placed after sArray.
  13. aString is a variable of type
  14. String .*/

A variable of type array can be assigned a reference of type array . If no array reference is assigned to a variable of type array , the value assigned to the variable of type array is null .

  1. int iArray[];
  2. /*
  3. iArray is a variable of type
  4. int[] .
  5. No array reference was assigned
  6. to iArray , as such it is
  7. assigned the null value .*/

To create an array , The notations :

can be used .

The notation {expression , expression ...} can only be used while declaring an array , while other notations can be used everywhere .

  1. jshell>
  2.  
  3. > String[] sArrayOne;
  4. /*
  5. Declare the sArrayOne variable , to
  6. be an array of type
  7. String .
  8. The sArrayOne variable is not
  9. initialized with any value
  10. that holds a reference to
  11. an array of type String[]
  12. ,as such it has a null
  13. value .*/
  14. sArrayOne ==> null
  15.  
  16.  
  17. > int[] iArrayOne , iArrayTwo = { 1, 2, 3+5 }
  18. /*
  19. Declare iArrayOne and iArrayTwo to
  20. be variables of type int[] .
  21. iArrayOne is not initialized , to
  22. any value which holds a reference
  23. to an array of type int[] . As
  24. such it has a null value .
  25. iArrayTwo is initialized using
  26. { 1, 2, 3+5 } .
  27. An array of type int[] is created .
  28. Its length is equal to the number of
  29. elements inside { 1, 2, 3+5 } .
  30. The expressions in { 1, 2, 3+5 }
  31. are evaluated and are assigned
  32. to the first , second and third
  33. element of the newly created array .
  34. A reference of the newly created array ,
  35. is stored inside iArrayTwo .*/
  36. iArrayOne ==> null
  37. iArrayTwo ==> [ 1, 2, 8 ]
  38.  
  39.  
  40. > Object[] oArrayOne , oArrayTwo = {new Object()};
  41. /*
  42. oArrayOne is a variable , of type
  43. Object[]. It is not initialized ,
  44. to hold a reference to an array
  45. of type Object[] , as such it
  46. is assigned a null value .
  47. oArrayTwo is a variable of type
  48. Object[]. It is initialized using
  49. {new Object()}.
  50. An array of type Object is created ,
  51. it has a length of 1 . The expression
  52. new Object is evaluated , it creates
  53. a new instance of Object . A reference
  54. of the newly created object is stored
  55. inside the first element of the newly
  56. created array .
  57. A reference of the newly created array
  58. is stored inside oArrayTo .*/
  59. oArrayOne ==> null
  60. oArrayTwo ==> [ java.lang.Object@59f99ea ]
  61.  
  62.  
  63. > oArrayOne = {new Object()}
  64. /*
  65. It is illegal to use
  66. {expression , expression ..}
  67. anywhere beside in array
  68. declaration .*/
  69. | Error:
  70. | illegal start of expression
  71. | oArrayOne = {new Object()}
  72.  
  73. > oArrayOne = oArrayTwo
  74. /*
  75. Assign the value of the variable
  76. oArrayTwo to oArrayOne .*/
  77. oArrayOne ==> [ java.lang.Object@59f99ea ]

When using the notation new Type[length_expression] , an array of the specified length and type is created , and all of its elements are null , unless the array is of the primitive type , in this case the element are initialized to their default value . For example the default value of int is 0.

The length expression must evaluate to a type int , and must be >=0 . As such the max length of an array that can be created is 2147483647 .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4. /*
  5. import the Arrays utility
  6. class .*/
  7.  
  8.  
  9. > String []sArray;
  10. /*
  11. Declare a variable of type
  12. String [] .
  13. It is not initialized ,
  14. as such its value is
  15. null .*/
  16. sArray ==> null
  17.  
  18.  
  19. > sArray = new String[3];
  20. /*
  21. Create an array of type String[]
  22. which has three elements
  23. initialized to null .
  24. A reference of this array is
  25. stored inside the variable
  26. sArray .*/
  27. sArray ==> [ null, null, null ]
  28.  
  29.  
  30. > int k = 1 ;
  31. > int j = 3 ;
  32. > int iArray[] = new int[k*j];
  33. /*
  34. Declare the iArray variable
  35. to be an array of type
  36. int .
  37. Evaluate the expression
  38. k*j , its value is 3 .
  39. Create a new array of
  40. length three , of type
  41. int , with all of its
  42. elements having a value
  43. of 0.
  44. Assign a reference of
  45. the newly created array
  46. to the variable iArray .*/
  47. iArray ==> [ 0, 0, 0 ]
  48.  
  49.  
  50. > char cArray[] = new char[2];
  51. /*
  52. Declare cArray to be a variable
  53. of type char[].
  54. Create a char array of length
  55. two , with all of its elements
  56. initialized to their default
  57. values .
  58. Assign a reference of the newly
  59. created array to the
  60. variable cArray .*/
  61. cArray ==> [ '\000', '\000' ]
  62.  
  63.  
  64. > Arrays.toString(new int[5])
  65. /*
  66. Create a new array of type int ,
  67. which has a length of 5 .
  68. Pass a reference to it ,
  69. to Arrays toString method .
  70. Arrays.toString method will print
  71. the elements contained in this
  72. array .*/
  73. [0, 0, 0, 0, 0]

When using the notation new Type[]{expression , expression ...} , an array of the given type and of the length of the {expression , expression ...} is created .

The expressions are evaluated. If the array type is primitive , the value of the expression is stored inside the array . If the array type is of the reference type , a reference to the evaluated value is stored .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4. /*
  5. import the Arrays utility
  6. class .*/
  7.  
  8.  
  9. > Arrays.toString(new int[]{ 1, 2, 3 })
  10. /*
  11. Create an anonymous array ,
  12. of type int .
  13. Its elements are initialized to
  14. the three elements 1 , 2 and 3 .
  15. Use the Arrays.toString method
  16. to print the value of each
  17. element in the newly created
  18. array .*/
  19. [ 1, 2, 3 ]
  20.  
  21.  
  22. > int[] iArrayOne = new int[]{}
  23. /*
  24. Declare iArrayOne to be a variable
  25. of type int [] .
  26. Create an new array of type
  27. int , containing no elements .
  28. Assign a reference to the
  29. newly created array to
  30. iArrayOne .*/
  31. iArrayOne ==> []

Variable of type multidimensional arrays can be created by adding brackets to the variable declaration , each additional brackets corresponds to an additional dimension .

  1. jshell>
  2.  
  3. > int[][] iArrayOne , iArratTwo;
  4. /*
  5. Create two variables of the type :
  6. int [][] .
  7. int[][] is an an array , which
  8. elements references arrays
  9. of the type int [] .*/
  10. iArrayOne ==> null
  11. iArratTwo ==> null
  12.  
  13.  
  14. > int iArrayOne[][] , iArratTwo;
  15. /*
  16. Declare a variable of the type :
  17. int [][] , and a variable of
  18. the type int .*/
  19. iArrayOne ==> null
  20. iArratTwo ==> 0

To create a multidimensional array , we can also use the methods describe earlier on .

  1. jshell>
  2.  
  3. /*
  4. Creating arrays using the notation
  5. {expression , expression ...} */
  6.  
  7. > int[][] iArray = { { 1, 2 } , { 1, 2, 3, 4 } };
  8. iArray ==> [ [ 1, 2 ] , [ 1, 2, 3, 4 ] ]
  9. /*
  10. Create a multi dimensional array of length
  11. 2 and of type int [][].
  12. Each element of this multidimensional array
  13. references an array of type int [].
  14. The first element reference an array of
  15. type int [] which has a length of 2 ,
  16. and which contains the elements 1
  17. and 2 .
  18. The second element also reference an array
  19. of type int[] which has a length of
  20. 4 , and contains the elements 1 2 3
  21. and 4 .
  22. Store a reference of the array of
  23. type int [][] into the variable
  24. iArray .*/
  25.  
  26.  
  27. /*
  28. Creating arrays using the notation
  29. new Type[length] .*/
  30. > String sArray[][];
  31. /*
  32. Declare a variable of type String[][] .*/
  33.  
  34. > sArray = new String[2][2]
  35. /*
  36. Create an array of type String[][]
  37. and of length two .
  38. It contain references to arrays of
  39. type String[] .
  40. The first element reference an array
  41. of type String[] , of length two ,
  42. which elements contains references to
  43. null .
  44. The second element reference an array
  45. of type String[] , of length two ,
  46. which elements contains references to
  47. null .
  48. Assign a reference to the array of type
  49. String[][] to the variable sArray .*/
  50. sArray ==> [ [ null, null ],[ null, null ] ]
  51.  
  52.  
  53. > sArray = new String[3][]
  54. /*
  55. Create an array of length 3 ,
  56. which elements hold references
  57. to arrays of type String[] .*/
  58. sArray ==> [ null , null , null ]
  59.  
  60. > sArray[0] = new String[]{ "hello", "arrays" };
  61. /*
  62. Each element of sArray , can be assigned
  63. an array of type String[]
  64. Create a new array of type String[] ,
  65. which elements reference the two
  66. String "hello" and "arrays".
  67. Store a reference to this array in
  68. sArray[0] .*/
  69.  
  70. > sArray
  71. sArray ==> [ [ "hello", "arrays" ], null, null ]
  72.  
  73.  
  74. /*
  75. Creating arrays using the notation
  76. new Type[]{expression , expression ...} .*/
  77.  
  78. > sArray = new String[][]{ { "hey", "java" }, { "chrome", "help" , "space" } }
  79. sArray ==> [ [ "hey", "java" ], [ "chrome", "help", "space" ] ]

2- Array length

An array length can be gotten using the .length property .

Example of accessing the array length of arrays having a single dimension.

  1. jshell>
  2.  
  3. > int []iArrayOne = {} , iArrayTwo = { 1, 2 } , iArrayThree;
  4. /*
  5. Declare three variables of type int[].
  6. iArrayOne contains a reference
  7. to an array which contains
  8. no elements.
  9. iArrayTwo contains a reference
  10. to an array which contains
  11. 2 elements.
  12. iArrayThree contains a reference
  13. to null .*/
  14. iArrayOne ==> []
  15. iArrayTwo ==> [ 1, 2 ]
  16. iArrayThree ==> null
  17.  
  18. > iArrayOne.length
  19. /*
  20. iArrayOne reference an array
  21. which contains no elements
  22. , the length of the array
  23. is 0 .*/
  24. 0
  25.  
  26. > iArrayTwo.length
  27. /*
  28. iArrayTwo reference an array
  29. which contains two elements ,
  30. as such its length is 2 .*/
  31. 2
  32.  
  33. > iArrathree.length
  34. /*
  35. iArrayThree does not reference
  36. any array . It contains a
  37. reference to a null value , as
  38. such it cannot access the
  39. length property .*/
  40. | Exception java.lang.NullPointerException
  41. | at (#26:1)

Example of accessing the array length of arrays having multiple dimensions .

  1. jshell>
  2.  
  3. > int[][] iArrayOne = new int[2][] , iArrayTwo , iArrayThree = { { 1, 2, 3 }, { } } ;
  4. /*
  5. Create three variables of type
  6. int [][] .
  7. The first variable references an
  8. array of length 2 , which elements
  9. references array of type int [] .
  10. The second variable is of type int[][] ,
  11. but does not reference any array of
  12. type int [][] , as such it
  13. references a null value.
  14. The third variable references an
  15. array of length 2 , which elements
  16. references an array of type
  17. int [] .*/
  18. iArrayOne ==> [ null, null ]
  19. iArrayTwo ==> null
  20. iArrayThree ==> [ [ 1, 2, 3 ], [ ] ]
  21.  
  22. > iArrayOne.length;
  23. /*
  24. The length of the array which
  25. elements contain references
  26. to arrays of type int[]
  27. is : */
  28. 2
  29.  
  30. > iArrayOne[0].length;
  31. /*
  32. The first element of the array
  33. referenced by iArrayOne does
  34. not reference any array
  35. of type int[] , as such it
  36. references a null value .
  37. Trying to access the length property
  38. of null will result in
  39. NullPointerException .*/
  40. Exception java.lang.NullPointerException
  41. | at (#5:1)
  42.  
  43. > iArrayTwo.length;
  44. /*
  45. iArrayTwo references a null value ,
  46. so trying to access the length
  47. property of a null value results
  48. in a null pointer exception. */
  49. | Exception java.lang.NullPointerException
  50. | at (#4:1)
  51.  
  52. > iArrayThree[1].length
  53. /*
  54. Access the first element of
  55. int[][] , which is {} an array
  56. of type int [] .
  57. Access its length property .*/
  58. 0

3- Assigning values to elements of an array

An array is formed of zero or more elements . Elements of an array can be assigned a value using the square notation , which takes an expression which is evaluated .

When an element of an array is assigned a value , the value is assigned based on the rules of assigning a primitive or a reference type .

If the value to be assigned is of the primitive type , then the primitive type value is copied and stored in the array .

  1. jshell>
  2.  
  3. > int []iArrayOne = new int[1];
  4. /*
  5. iArrayOne is a variable of type int[] .
  6. new int[1] , creates an array
  7. of the primitive type int ,
  8. of length 1 .
  9. The elements of the newly created
  10. array are initialized to the
  11. default value 0 .
  12. A reference to the newly created
  13. array is stored inside iArrayOne .*/
  14. iArrayOne ==> [ 0 ]
  15.  
  16.  
  17. > iArrayOne[1-1] = 10 ;
  18. /*
  19. 1 - 1 is evaluated to 0 .
  20. The first element of the
  21. array reference by iArrayOne
  22. is assigned the value 10 .
  23. 10 is a primitive value ,
  24. as such it is copied and
  25. stored inside the array .*/
  26.  
  27.  
  28. > int anInt = 1 ;
  29. /*
  30. anInt contains the value
  31. 1 .*/
  32.  
  33.  
  34. > iArrayOne[0] = anInt ;
  35. /*
  36. The value contained in anInt
  37. is copied to iArrayOne[0] .
  38. anInt contains 1 , as such
  39. iArrayOne[0] contains 1 .*/
  40.  
  41.  
  42. > iArrayOne
  43. /*
  44. iArrayOne is a variable which
  45. references an array of type
  46. int[] , and which contains
  47. the element 1 .*/
  48. iArrayOne ==> [1]

If the value to be assigned is a reference type , then the reference is copied and stored inside the array .

  1. jshell>
  2.  
  3. > String aString = "hello";
  4. /*
  5. Create a variable of type
  6. String .
  7. Assign a reference of
  8. the String "hello" to
  9. aString .*/
  10.  
  11. > String[] sArray = {aString};
  12. /*
  13. sArray is a variable of type
  14. String [] .
  15. it is initialized using
  16. {aString} .
  17. A new array of type String[]
  18. and of length 1 is created .
  19. aString is a reference type ,
  20. as such the value of aString ,
  21. which is a reference , is stored
  22. inside the first element of
  23. sArray .
  24. A reference of the newly created
  25. array is stored inside the
  26. variable sArray .
  27. sArray[0] and aString contain the
  28. same reference .*/
  29.  
  30. > sArray[0] = "hey"
  31. /*
  32. "hey" is a string literal ,
  33. a reference for the String
  34. "hey" is stored inside
  35. sArray[0] .
  36. sArray[0] and aString do not
  37. contain the same reference
  38. anymore .*/
  39. sArray[0] ==> "hey"
  40.  
  41. > aString
  42. /*
  43. aString is still referencing the
  44. String literal "hello"*/
  45. aString ==> "hello"
  46.  
  47. /*
  48. String are immutable , so their
  49. values cannot change .*/
  50.  
  51.  
  52. > class WWW{
  53. String address;
  54. }
  55. /*
  56. Create the WWW class , with one
  57. field of type String . */
  58.  
  59. > WWW aWWW = new WWW();
  60. /*
  61. Create a new instance of WWW ,
  62. and store a reference to
  63. it in the variable aWWW .
  64. aWWW address attribute is initialized ,
  65. to null. */
  66. aWWW ==> WWW@6ddf90b0
  67.  
  68. > aWWW.address
  69. aWWW.address ==> null
  70.  
  71. > WWW wwwArray[] = {aWWW};
  72. /*
  73. wwwArray is a variable of
  74. type WWW[] .
  75. A new array is created ,
  76. of type WWW and of length
  77. 1 .
  78. The reference contained in
  79. the variable aWWW , is copied
  80. and stored inside aWWW[0].
  81. aWWW[0] and the variable
  82. aWWW contain the same reference .
  83. A reference of the newly created
  84. array is stored in the
  85. wwwArray variable .*/
  86. wwwArray ==> [ WWW@6ddf90b0 ]
  87.  
  88. > wwwArray[0].address = "http://difyel.com";
  89. /*
  90. wwwArray[0] address field is
  91. assigned the value of
  92. "http://difyel.com" .*/
  93. wwwArray[0].address ==> "http://difyel.com"
  94.  
  95. > aWWW.address
  96. /*
  97. aWWW refers to the same object ,
  98. referenced by wwwArray[0] . As
  99. such aWWW.address field has a
  100. value of http://difyel.com .*/
  101. aWWW.address ==> "http://difyel.com"
  102.  
  103. > aWWW = new WWW();
  104. /*
  105. A new instance of WWW is
  106. created . Its reference is
  107. assigned to the variable
  108. aWWW .*/
  109. aWWW ==> WWW@369f73a2
  110. /*
  111. aWWW and wwwArray[0] do not refer to
  112. the same object . So changing
  113. the field value of aWWW , will
  114. not affect the field value
  115. of wwwArray[0] and the inverse
  116. is also true .*/
  117.  
  118.  
  119. > int[][] iArrayOne = new int[2][];
  120. /*
  121. Declare a variable iArrayOne
  122. of the type int[][] .
  123. Create an array of length 2 ,
  124. which elements reference an array
  125. of type int [] .
  126. Assign a reference to the newly created
  127. array inside the variable
  128. iArrayOne .*/
  129. iArrayOne ==> [ null, null ]
  130.  
  131. > iArrayOne[0] = new int[1] ;
  132. /*
  133. Create an array of type int[]
  134. of length 1 .
  135. Store a reference to the newly
  136. created array to iArrayOne[0] .*/
  137.  
  138. > iArrayOne[0][0] = 1
  139. /*
  140. Access the first array of type
  141. int[] .
  142. Store inside the first element
  143. of the array of type int[] ,
  144. the value 1 .*/

4- Accessing the elements of an array

Elements of an array can be accessed using the square brackets notation , which takes an int value >=0 and less than the length of the array .

  1. jshell>
  2.  
  3. > int[] iArray = new int[]{ 0, 1, 2 }
  4. /*
  5. iArray is a variable of type int[].
  6. It is assigned a reference to an
  7. array of length 3 and of type
  8. int[] .*/
  9. iArray ==> [ 0, 1, 2 ]
  10.  
  11. > iArray[0]
  12. /*
  13. Access the first element
  14. of the array referenced by
  15. iArray[0] .*/
  16. iArray[0] ==> 0
  17.  
  18. > iArray[0+2]
  19. /*
  20. 0+2 is evaluated to 2 .
  21. Access the third element
  22. of the array referenced by
  23. iArray[2] .*/
  24. iArray[2] ==> 2
  25.  
  26. > iArray[3]
  27. /*
  28. An ArrayIndexOutOfBoundsException is
  29. thrown , when trying to access an element
  30. with index <0 or >= length of the array .*/
  31. | Exception java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
  32. | at (#3:1)
  33.  
  34. > iArray[-1]
  35. | Exception java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
  36. | at (#4:1)
  37.  
  38.  
  39. > int iArrayTwo[][] = {{}}
  40. /*
  41. Create an array which references
  42. an array of type int [] .
  43. The array of type int[] does not
  44. contain any elements .
  45. Store a reference of the newly
  46. created array inside the
  47. variable iArrayTwo .*/
  48. iArrayTwo ==> [ [ ] ]
  49.  
  50. > iArrayTwo[0][0]
  51. /*
  52. Access the first element of
  53. the array referenced by the
  54. variable iArrayTwo .
  55. Access the first element
  56. referenced by the array of type
  57. int [] .
  58. There is no elements found in
  59. the array of type int[] ,
  60. as such an index out of
  61. bound exception is thrown .*/
  62. | Exception java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
  63. | at (#5:1)

5- Looping through arrays

To loop through an array , a for loop can be used as follows .

  1. jshell>
  2.  
  3. > int iArray[] = {1, 2, 3 }
  4. /*
  5. iArray is a variable of type int[] .
  6. It holds a reference to an array
  7. of three elements 1 , 2 and 3 .*/
  8. iArray ==> [ 1, 2, 3 ]
  9.  
  10. > /* Loop through the array using a for loop */
  11. for( int i = 0 ; i < iArray.length ; i++ )
  12. {
  13. int elementAtIndexI = iArray[i];
  14. /*
  15. do something , for example
  16. print the array elements .*/
  17. System.out.println(elementAtIndexI);
  18. }
  19. 1
  20. 2
  21. 3
  22.  
  23.  
  24. > int iArrayTwo[][] = { { 1, 2 }, { 3, 4 } }
  25. /*
  26. iArrayTwo is a variable of type
  27. int[][] . It hold a reference to
  28. an array of type int[][].
  29. The array of type int[][] has a
  30. length of two , and contains
  31. references to two arrays of
  32. type int[] .
  33. The arrays of type int[] , each
  34. contain two int elements .*/
  35. iArrayTwo ==> [ [ 1, 2 ], [ 3, 4 ] ]
  36.  
  37. > /* For each additional dimension ,
  38. an additional for loop must
  39. be added .*/
  40. for( int i = 0 ; i < iArrayTwo.length ; i++ )
  41. {
  42. for( int j = 0 ; j < iArrayTwo[i].length ; j++ )
  43. {
  44. int elementAtIndexIJ = iArrayTwo[i][j];
  45. /*
  46. Do something , for example
  47. print the array elements .*/
  48. System.out.println(elementAtIndexIJ);
  49. }
  50. }
  51. 1
  52. 2
  53. 3
  54. 4

A for each loop can also be used to loop through an array . The difference between a for and a for each loop , is that in a for each loop it is not necessary to declare the index used to loop through the array , but at the same time this means no access to the index .

A for and a for each loop can be mixed .

  1. jshell>
  2.  
  3. > String sArray[] = { "Hello", "Search" }
  4. /*
  5. sArray is a variable of type
  6. String [] .
  7. It holds a reference to an array
  8. of type String [] .
  9. The array of type String []
  10. holds two references for
  11. Strings .*/
  12. sArray ==> [ "Hello", "Search" ]
  13.  
  14. > /* Loop through an array using a for each loop */
  15. for( String element : sArray )
  16. {
  17. /*
  18. do something , with the
  19. element .*/
  20. System.out.println(element);
  21. }
  22. Hello
  23. Search
  24.  
  25.  
  26. > String sArrayOne[][] = { {"java"} , {"red" , "green"} }
  27. /*
  28. sArrayOne is a variable of type String [][] .
  29. It hold a reference to an array which
  30. contains two references to arrays of
  31. type String[] .*/
  32. sArrayOne ==> [ [ "java" ] , [ "red", "green" ] ]
  33.  
  34. > for( String[] stArray : sArrayOne )
  35. {
  36. for(String sElem : stArray)
  37. {
  38. /*
  39. Do something with the element .*/
  40. System.out.println(sElem);
  41. }
  42. }
  43. java
  44. red
  45. green

A Spliterator can also be used to loop through an array . As its name convey , a Spliterator is an iterator which can be split . It allows to perform looping one element at a time using its tryAdvance method , or for all the remaining elements using its forEachRemaining method , or to obtain another Spliterator from this Spliterator using the trySplit method , which ideally may try to split the Spliterator in half , but might split it at other points , or might fail .

A Spliterator source must not be modified , if it does not have the immutable or concurrent characteristics .

A Spliterator can be iterated over only once .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4. > import java.util.Spliterator;
  5.  
  6.  
  7. > int iArray[] = { 1, 2, 3, 4 } ;
  8. /*
  9. iArray is a variable which contains
  10. a reference to an array of
  11. type int [] .*/
  12. iArray ==> [ 1, 2, 3, 4 ]
  13.  
  14. > Spliterator<Integer> iSpliterator = Arrays.spliterator(iArray);
  15. /*
  16. Use Arrays.spliterator to create a
  17. Spliterator which has a source ,
  18. the array referenced by
  19. iArray .*/
  20. iSpliterator ==> java.util.Spliterators$IntArraySpliterator@68be2bc2
  21.  
  22. > iSpliterator.hasCharacteristics(Spliterator.IMMUTABLE)
  23. /*
  24. Using hasCharacteristics , check
  25. if the created Spliterator
  26. has the characteristic of being
  27. Immutable .*/
  28. $ ==> true
  29.  
  30. > iSpliterator.hasCharacteristics(Spliterator.CONCURRENT)
  31. /*
  32. Using hasCharacteristics , check
  33. if the created Spliterator
  34. has the characteristic of being
  35. Concurrent .*/
  36. $ ==> false
  37.  
  38. > iSpliterator.hasCharacteristics(Spliterator.NONNULL)
  39. /*
  40. Using hasCharacteristics , check
  41. if the Source guarantees
  42. that encountered elements
  43. will not be null .*/
  44. $ ==> false
  45.  
  46. > iSpliterator.hasCharacteristics(Spliterator.ORDERED)
  47. /*
  48. Using hasCharacteristics , check
  49. if an encounter order
  50. is defined for the
  51. elements .*/
  52. $ ==> true
  53.  
  54. > iSpliterator.tryAdvance(System.out::println)
  55. /*
  56. Using the tryAdvance method , try
  57. to advance one element in the
  58. Spliterator .
  59. Returns true on success , false
  60. on failure.
  61. Pass the println function as argument
  62. to tryAdvance , to print the
  63. element .*/
  64. 1
  65. $ ==> true
  66.  
  67. > int index = 1 ;
  68. /*
  69. Declare a variable containing the
  70. current index of the
  71. Spliterator .*/
  72.  
  73. > iSpliterator.forEachRemaining( iElement -> {
  74. System.out.println(iElement);
  75. if(index < iArray.length - 1)
  76. iArray[++index] *= 2;
  77. } )
  78. /*
  79. Use forEachRemaining , to loop
  80. through the remaining elements
  81. of the Spliterator .
  82. Pass a lambda function to
  83. forEachRemaining, which takes
  84. as argument : iElement , the
  85. current iterating element , print
  86. it , and modify the next element
  87. by doubling it .*/
  88. 2
  89. 6
  90. 8
  91.  
  92.  
  93. > String [][]sArray = { { "ae", "ar" }, { "be", "br" }, { "ce", "ck" } }
  94. /*
  95. Create an array of type
  96. String [][] . It contains
  97. three references to arrays
  98. of types String [] . Each
  99. contains two references to
  100. Strings .*/
  101. sArray ==> [ [ "ae", "ar" ] , ["be" , "br"] , [ "ce", "ck" ] ]
  102.  
  103. > Spliterator<String []> saSpliterator = Arrays.spliterator(sArray , 1 , 3 ) ;
  104. /*
  105. Use Arrays.spliterator , to create
  106. a Spliterator which has a
  107. source the array referenced by
  108. the variable sArray , starting
  109. from index 1 inclusive , till
  110. index 3 non inclusive .*/
  111.  
  112. > Spliterator<String []> splitSaSplitIerator = saSpliterator.trySplit();
  113. /*
  114. Use trySplit to split the
  115. Spliterator which has a source
  116. the array referenced by sArray .
  117. Store a reference to the created
  118. Spliterator in the variable
  119. splitSaSplitIerator .*/
  120.  
  121. > saSpliterator.forEachRemaining(
  122. aElement -> {
  123. for(String sElement : aElement)
  124. System.out.println(sElement);
  125. })
  126. /*
  127. Use forEachRemaining , to loop
  128. through the elements of the
  129. Spliterator referenced by
  130. the variable saSpliterator .
  131. Pass in a lambda function ,
  132. which takes one argument ,
  133. of type String [] : aElement .
  134. Loop through aElement , which
  135. is an array of type String [] ,
  136. using a for each loop .
  137. Print the values referenced
  138. by the elements of the
  139. array of type String[] .*/
  140. ce
  141. ck
  142.  
  143. > splitSaSplitIerator.forEachRemaining(
  144. aElement -> {
  145. for(String sElement : aElement)
  146. System.out.println(sElement);
  147. })
  148. /*
  149. Use forEachRemaining to loop
  150. through the elements of the
  151. Spliterator referenced by
  152. splitSaSplitIerator . They
  153. are of type String [] .
  154. Pass in a lambda function ,
  155. which takes one argument
  156. of type String[] : aElement .
  157. Loop through the elements
  158. of the array referenced by
  159. the variable aElement .
  160. Each element contains a
  161. reference to a String .
  162. Print the String . */
  163. be
  164. br

Also a Stream can be obtained from an array , and it can be used to loop over the element of the array . A Stream can only be iterated over once .

  1. jshell>
  2.  
  3. > import java.util.Arrays ;
  4. > import java.util.stream.IntStream ;
  5. > import java.util.stream.Stream ;
  6.  
  7. > int iArray[] = { 0, 3, 1, 2 };
  8. /*
  9. Create an array of type int[]
  10. , which has 4 elements .
  11. Store a reference to it in
  12. the variable iArray .*/
  13. iArray ==> [ 0, 3, 1, 2 ]
  14.  
  15. > IntStream iStream = Arrays.stream(iArray);
  16. /*
  17. Use Arrays.stream , to create
  18. a sequential Stream .
  19. It has a source the array
  20. referenced by the variable
  21. iArray .*/
  22. iStream ==> java.util.stream.IntPipeline$Head@29ee9faa
  23.  
  24. > iStream.forEach(System.out::println);
  25. /*
  26. Iterate over the stream using
  27. the forEach method.
  28. The forEach method takes as
  29. argument the function println ,
  30. and use it to print the
  31. stream .*/
  32. 0
  33. 3
  34. 1
  35. 2
  36.  
  37. > iStream = Arrays.stream(iArray);
  38. /*
  39. Using Arrays.stream , create
  40. a sequential stream , which
  41. source is the array referenced
  42. by iArray .*/
  43.  
  44. > iStream.parallel().forEach(System.out::println);
  45. /*
  46. Create a parallel Stream from the
  47. sequential stream referenced by
  48. the variable iStream.
  49. The forEach method does not guarantee
  50. the order of encounter as defined
  51. in the Stream source for parallel
  52. streams .*/
  53. 1
  54. 2
  55. 3
  56. 0
  57.  
  58. > iStream = Arrays.stream(iArray);
  59. /*
  60. Use Arrays.stream to create
  61. a sequential stream , which
  62. source is the array referenced
  63. by iArray .*/
  64.  
  65. > iStream.parallel().forEachOrdered(System.out::println);
  66. /*
  67. Create a parallel Stream from the
  68. sequential stream referenced
  69. by the variable iStream .
  70. Iterate over the parallel Stream using
  71. forEachOrdered .
  72. The forEachOrdered guarantees the order
  73. of encounter as defined in the Stream
  74. source for parallel Streams. */
  75. 0
  76. 3
  77. 1
  78. 2
  79.  
  80.  
  81. > String[][] sArray = { { "aa", "ab" }, { "cd", "c" } }
  82. /*
  83. Create an array of type String[][]
  84. and assign a reference to it
  85. to the variable sArray .*/
  86. sArray ==> [ [ "aa", "ab" ], [ "cd", "c" ] ]
  87.  
  88. > Stream<String[]> saStream = Arrays.stream(sArray , 1 , 2);
  89. /*
  90. Use Arrays.stream to create a
  91. sequential Stream which has a
  92. source the array referenced by
  93. sArray , starting at index 1
  94. inclusive , ending index 2
  95. exclusive .*/
  96. saStream ==> java.util.stream.ReferencePipeline$Head@6f7fd0e6
  97.  
  98. > saStream.forEach( aString -> Arrays.stream(aString).forEach(System.out::println));
  99. /*
  100. Iterate over the Stream using
  101. forEach Method.
  102. Pass in a lambda function , which
  103. takes as argument an element of
  104. type String[] .
  105. Create a Stream from this element ,
  106. and use the forEach method , to
  107. iterate over its elements .
  108. Pass to the forEach method ,
  109. the println function to print
  110. the elements .*/
  111. cd
  112. c

6- Printing arrays

The Arrays.toString , and Arrays.deepToString , can be used to get a String representation of an array . The Arrays.deepToString will get the String representation of arrays containing other arrays .

  1. jshell>
  2.  
  3. > int iArray[][] = { { 1, 2 }, { 3, 4 } }
  4. /*
  5. Create an array of type int [][] ,
  6. and store a reference to it
  7. in the variable iArray .*/
  8. iArray ==> [ [ 1, 2 ], [ 3, 4 ] ]
  9.  
  10. > Arrays.toString(iArray)
  11. /*
  12. Use Arrays.toString to get a
  13. toString representation of
  14. the array referenced by the
  15. variable iArray .*/
  16. $ ==> "[[I@58651fd0, [I@4520ebad]"
  17.  
  18. > Arrays.deepToString(iArray)
  19. /*
  20. Use Arrays.deepToString to
  21. get a deep toString
  22. representation of the array ,
  23. referenced by the variable
  24. iArray .*/
  25. $ ==> "[[1, 2], [3, 4]]"

7- Copying and cloning arrays

The clone method can be used to clone an array . This will return a shallow copy of the elements of the array .

If the array is an array of primitive types , this works well . If the array is of reference type , this means the elements of the array and its clone contains the same references , as such they share the same objects .

  1. jshell>
  2.  
  3. > int iArray[] = { 1, 2, 4 };
  4. /*
  5. Create an array of type
  6. int[] which contains
  7. three integers .
  8. Store a reference to it
  9. in the variable
  10. iArray .*/
  11. iArray ==> [ 1, 2, 4 ]
  12.  
  13. > int iArrayClone[] = iArray.clone()
  14. /*
  15. Create a new array , and
  16. shallow copy the elements
  17. 1 , 2 and 4 , of the array
  18. referenced by the iArray
  19. variable .
  20. Store a reference of the
  21. newly created array in
  22. iArrayClone .*/
  23. iArrayClone ==> [ 1, 2, 4 ]
  24.  
  25.  
  26. > Object oArray[] = { new Object(), new Object() }
  27. /*
  28. Create an array of type
  29. Object[] , and which contains
  30. two elements .
  31. Store the reference of
  32. this array in the variable
  33. oArray .*/
  34. oArray ==> [ java.lang.Object@4520ebad, java.lang.Object@5419f379 ]
  35.  
  36. > Object oArrayClone[] = oArray.clone();
  37. /*
  38. Shallow copy the elements of
  39. the array referenced by
  40. oArray , into a new array of
  41. type Object[] .
  42. They are of reference type , as
  43. such shallow copy the
  44. references .
  45. Store the reference of the newly
  46. created array inside
  47. oArrayClone .
  48. The elements of the arrays
  49. referenced by the oArray ,
  50. and oArrayClone variable
  51. refer to the same Objects .*/
  52. oArrayClone ==> [ java.lang.Object@4520ebad, java.lang.Object@5419f379 ]
  53.  
  54.  
  55. > int iArrayTwo [][] = { {1, 2, 3 }, { 0 } }
  56. /*
  57. Create an array of length 2 ,
  58. which elements refers to
  59. arrays of type int [] .
  60. Store a reference to this
  61. array , in the variable
  62. iArrayTwo .*/
  63. iArrayTwo ==> [ [ 1, 2, 3 ], [ 0 ] ]
  64.  
  65. > int[][] iArrayTwoClone = iArrayTwo.clone();
  66. /*
  67. Create a shallow copy of the array
  68. referenced by the variable
  69. iArrayTwo .
  70. A new array which elements can
  71. hold a reference to arrays of
  72. type int [] is created .
  73. The elements of the array referenced
  74. by the iArrayTwo variable are
  75. copied .
  76. They contain references to arrays of
  77. type int [].
  78. Store a reference of the newly
  79. created array in the variable
  80. iArrayTwoClone .
  81. The elements of the arrays referenced
  82. by iArrayTwo and iArrayTwoClone ,
  83. reference the same arrays of type
  84. int [] .*/
  85. iArrayTwoClone ==> [ [ 1, 2, 3 ], [ 0 ] ]
  86.  
  87. > iArrayTwo[1][0] = 3
  88. /*
  89. Access the second element of the
  90. array referenced by the variable
  91. iArrayTwo.
  92. Assign to this array first
  93. element the value of 3 .*/
  94.  
  95. > iArrayTwoClone
  96. /*
  97. Print the array referenced by
  98. the variable iArrayTwoClone .
  99. The arrays referenced by the
  100. variables iArrayTwoClone
  101. and iArrayTwo , contain
  102. the same references .
  103. iArrayTwoClone[1][0] is equal
  104. also to 3 .*/
  105. iArrayTwoClone ==> [ [ 1, 2, 3 ] ,[ 3 ] ]

Another method to create a shallow copy of an array , is by using the System.arraycopy method .

  1. public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Its first argument is the source array to copy from . Its second argument is the index from which to start copying from the source array . Its third argument is the array to copy to . Its fourth argument is the index from which to start copying at the destination array . Its fifth argument is the number of elements to copy .

The difference between this method and the clone method , is that this method can be used to copy just a portion of an array , or the whole array , and that both arrays must exists or be created before performing the copying .

  1. jshell>
  2.  
  3. > int [] iArray = { 10, 1, 2, 34, 12 }
  4. /*
  5. Create an array of type int[]
  6. and store a reference to it
  7. in the variable iArray .*/
  8. iArray ==> [ 10, 1, 2, 34, 12 ]
  9.  
  10. int [] iArrayCopy = new int[2]
  11. /*
  12. Create an aray of length 2 ,
  13. of type int[].
  14. Store a reference to it inside
  15. iArrayCopy .*/
  16. iArrayCopy ==> [ 0, 0 ]
  17.  
  18.  
  19. > System.arraycopy(iArray , 2 , iArrayCopy , 0 , 2 )
  20. /*
  21. Using System.arraycopy , copy
  22. from the array referenced
  23. by iArray , starting at index
  24. 2 , to the array referenced by
  25. iArrayCopy , starting at index
  26. 0 , two elements .*/
  27.  
  28. > iArrayCopy
  29. iArrayCopy ==> [ 2, 34 ]
  30.  
  31.  
  32. > int iArrayTwo[][] = { {}, {1 , 2} }
  33. /*
  34. Create an array of length 2 ,
  35. which elements contains
  36. references to arrays of
  37. type int [] .*/
  38. iArrayTwo ==> [ [ ], [ 1, 2 ] ]
  39.  
  40. > int iArrayTwoCopy[][] = new int[4][]
  41. /*
  42. Create an array of length 4 ,
  43. which elements contain
  44. references to arrays of
  45. types int[] .*/
  46. iArrayTwoCopy ==> [ null, null, null, null ]
  47.  
  48. > System.arraycopy(iArrayTwo , 0 , iArrayTwoCopy , 0 , 2 )
  49. /*
  50. Use System.arraycopy to copy
  51. from the array referenced by
  52. iArrayTwo , starting at index 0 ,
  53. to the array referenced by
  54. iArrayTwoCopy , starting at
  55. position 0 , 2 elements .
  56. The elements which are copied are
  57. references to arrays of type
  58. int [] .*/
  59.  
  60. > iArrayTwoCopy
  61. iArrayTwoCopy ==> [ [ ], [ 1, 2 ], null, null ]

The source and destination array can be the same . System.araycopy proceeds as if there is a temporary array .

  1. jshell>
  2.  
  3. > int [] iArray = { 10, 1, 2, 34, 12 }
  4. iArray ==> [ 10, 1, 2, 34, 12 ]
  5.  
  6. > System.arraycopy(iArray , 2 , iArray , 0 , 3 )
  7. /*
  8. Use System.arraycopy , to copy from
  9. the array referenced by iArray ,
  10. starting at index 2 , to itself ,
  11. starting at index 0 ,
  12. three elements .*/
  13.  
  14. > iArray
  15. iArray ==> [ 2, 34, 12, 34, 12 ]

An IndexOutOfBoundsException is thrown , when any of the source or destination indexes are negative , or larger than the source or destination array length .

An IndexOutOfBoundsException is also thrown , when the srcPos + length is greater than the source array length , or when the destPost + length is greater than the destination array length .

An IndexOutOfBoundsException is also thrown when the length is negative .

If an IndexOutOfBoundsException is thrown the destination array is not modified .

  1. jshell>
  2.  
  3.  
  4. > int [] iArray = { 10, 1, 2, 34, 12 }
  5. /*
  6. Create an array of five elements
  7. of type int[] , and store
  8. a reference to it in the
  9. variable iArray .*/
  10. iArray ==> [ 10, 1, 2, 34, 12 ]
  11.  
  12. > System.arraycopy(iArray , 2 , iArray , 0 , 10 )
  13. /*
  14. Use System.arraycopy to copy from
  15. the array reference by the
  16. variable iArray starting at position
  17. 2 , to itself starting position
  18. 0 , 10 elements.
  19. IndexOutOfBoundsException is
  20. thrown because 12 is larger
  21. then the length of the source
  22. array .*/
  23. | Exception java.lang.ArrayIndexOutOfBoundsException: arraycopy: last source index 12 out of bounds for int[5]
  24. | at System.arraycopy (Native Method)
  25. | at (#11:1)
  26.  
  27. > iArray
  28. /*
  29. The array referenced by
  30. iArray is not
  31. modified .*/
  32. iArray ==> int[5] { 10, 1, 2, 34, 12 }

A NullPointerException is thrown if the variables pointing to the source or destination arrays are null .

  1. jshell>
  2.  
  3. > int[] iArray = { 10, 1, 2, 34, 12 }
  4. /*
  5. Create an array of type int [] ,
  6. containing five elements .
  7. Store a reference to it inside
  8. the variable iArray .*/
  9. iArray ==> [ 10, 1, 2, 34, 12 ]
  10.  
  11. > int[] iArrayCopy;
  12. /*
  13. Declare a variable iArrayCopy ,
  14. of type int [] .
  15. It is assigned a null value .*/
  16. iArrayCopy ==> null
  17.  
  18. > System.arraycopy(iArray , 0 , iArrayCopy , 0 , 5 )
  19. /*
  20. iArrayCopy is a variable which does
  21. not refer to an array , it contains
  22. a null reference , as such
  23. System.arraycopy throws a null
  24. exception .*/
  25. | Exception java.lang.NullPointerException
  26. | at System.arraycopy (Native Method)
  27. | at (#3:1)

An ArrayStoreException is thrown when the source or destination are not of type array , or when the source or destination are arrays of different primitive types , or when one is an array of primitive type and the other is an array of reference type . In these cases the destination array is not modified .

  1. jshell>
  2.  
  3. > int iArray[] = { 10, 2, 33, 4, 1 }
  4. /*
  5. Create an array of type int[]
  6. formed of five elements.
  7. Store a reference to it inside
  8. the iArray variable .*/
  9. iArray ==> [ 10, 2, 33, 4, 1 ]
  10.  
  11. > System.arraycopy(new Object(), 0 , iArray , 2 , 3 )
  12. /*
  13. ArrayStoreException is thrown
  14. because the source is not
  15. of type array .*/
  16. | Exception java.lang.ArrayStoreException: arraycopy: source type java.lang.Object is not an array
  17. | at System.arraycopy (Native Method)
  18. | at (#2:1)
  19. > iArray
  20. /*
  21. The array reference by iArray
  22. was not modified .*/
  23. iArray ==> [ 10, 2, 33, 4, 1 ]

An ArrayStoreException is is also thrown when both the source and the destination are arrays of the reference type , and an element referenced by the source array cannot be converted to the destination array , elements type . In this case the destination array is modified till when the exception occurs .

  1. jshell>
  2.  
  3. > Object oArray[] = {new Integer(1), new Object() }
  4. /*
  5. Create an array of type Object[] ,
  6. formed of two elements .
  7. Store a reference to this array
  8. inside the variable oArray .*/
  9. oArray ==> [ 1 , java.lang.Object@64bfbc86 ]
  10.  
  11. > Integer iArray[] = new Integer[2]
  12. /*
  13. Create an array of type Integer[]
  14. of length 2 .
  15. Store a reference to it inside the
  16. variable iArray .*/
  17. iArray ==> [ null, null ]
  18.  
  19. > System.arraycopy(oArray , 0 , iArray , 0 , 2 )
  20. /*
  21. Use System.arraycopy to copy from
  22. the array referenced by oArray
  23. starting index 0 , to the array
  24. referenced by iArray starting index
  25. 0 , 2 elements .
  26. ArrayStoreException is thrown because
  27. an Object cannot be stored inside
  28. an Integer array .*/
  29. | Exception java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.Integer
  30. | at System.arraycopy (Native Method)
  31. | at (#5:1)
  32.  
  33. > iArray
  34. /*
  35. Only one element is copied from
  36. the array referenced by oArray
  37. to iArray .*/
  38. iArray ==> [ 1, null ]

A shallow copy of an array , can also be created using the Stream toArray method .

  1. jshell>
  2. > import java.util.Arrays;
  3.  
  4. > int iArray[] = { 1, 2, 34 };
  5. /*
  6. Create an array of type int[] ,
  7. and store a reference to it
  8. inside the variable iArray .*/
  9. iArray ==> [ 1 , 2 , 34 ]
  10.  
  11. > int iArrayClone[] = Arrays.stream(iArray).toArray();
  12. /*
  13. For primitive types : double , int , long ,
  14. Arrays.stream create a stream of type
  15. DoubleStream IntStream and LongStream .
  16. Use the toArray method to collect
  17. the elements of the Stream into
  18. an array .*/
  19. iArrayClone ==> [ 1, 2, 34 ]
  20.  
  21.  
  22. > String sArray[][] = { {"ae" , "df"}, {"oo", "on"} }
  23. /*
  24. Create an array of type String [][] , and
  25. store a reference to it in the variable
  26. sArray .*/
  27. sArray ==> [ [ "ae", "df" ] , [ "oo", "on" ] ]
  28.  
  29. > String sArrayClone[][] = Arrays.stream(sArray).toArray(String[][]::new);
  30. /*
  31. Use Arrays.stream method , to
  32. create a sequential stream
  33. backed by the array
  34. referenced by sArray .
  35. Use the toArray method , to return
  36. an array containing the elements
  37. of the Stream .
  38. Pass in the function which will be used
  39. to create the array , of the specified
  40. type.
  41. The function receive as a
  42. parameter the length of the
  43. to be created array .*/
  44. sArrayClone ==> [ [ "ae", "df" ], [ "oo", "on" ] ]

8- Merging arrays

There is no inbuilt java method to merge multiple arrays , a possible solution is as follows .

  1. jshell>
  2. > import java.lang.reflect.Array;
  3.  
  4. > /*Create a Class named MergeArrays*/
  5. class MergeArrays
  6. {
  7.  
  8. public static Object mergeArrays(Object ... oElements)
  9. {
  10. if(oElements.length == 0)
  11. /*
  12. If no arguments were provided ,
  13. return null .*/
  14. return null ;
  15. int length = 0 ;
  16.  
  17. for( int i = 0 ; i < oElements.length ; i++ )
  18. {
  19. /*
  20. check that oElements types are arrays .
  21. Check that the arrays referred by
  22. oElements , have the same Component
  23. types or that their component type
  24. is a subtype of the component type
  25. of oElements[0] .
  26. Get the length of the arrays referred
  27. by oElements , and calculate
  28. the total length of the to be newly
  29. created array .*/
  30. if(! oElements[i].getClass().isArray())
  31. throw new IllegalArgumentException("All elements must be arrays");
  32. if(! oElements[0].getClass().getComponentType().isAssignableFrom(oElements[i].getClass().getComponentType()))
  33. throw new IllegalArgumentException("oElements[" + i + "] component type is not a subclass or class of oElements[0] component type");
  34. length += Array.getLength(oElements[i]);
  35. }
  36.  
  37. Object rASrray = Array.newInstance(oElements[0].getClass().getComponentType(), length);
  38. System.arraycopy(oElements[0] , 0 , rASrray , 0 , Array.getLength(oElements[0]));
  39. for(int i = 1 ; i < oElements.length ; i++)
  40. {
  41. System.arraycopy(oElements[i] , 0 , rASrray , Array.getLength(oElements[i-1]) , Array.getLength(oElements[i]));
  42. }
  43. return rASrray;
  44. }
  45. }
  46.  
  47. > int iArray[] = (int []) MergeArrays.mergeArrays( new int[]{ 0, 1 }, new int[]{ 2, 3 } )
  48. iArray ==> [ 0, 1, 2, 3 ]
  49.  
  50. > String sArray[][] = (String [][] )MergeArrays.mergeArrays( new String[][]{ {"hello"}, {"world"} } , new String[][]{ { "df", "8" } } )
  51. sArray ==> [ [ "hello" ], [ "world" ], [ "df", "8" ] ]

arrays can also be merged by using the Stream API .

  1. jshell>
  2.  
  3. > import java.util.stream.Stream;
  4.  
  5. > Stream<int []> iaStream = Stream.of(new int[]{ 1, 2, 3 }, new int[]{ 5, 9, 12 })
  6. /*
  7. Create using the Stream.of
  8. method a sequential
  9. stream whose elements are
  10. of type int [] .*/
  11. iaStream ==> java.util.stream.ReferencePipeline$Head@4678c730
  12.  
  13. > int iaMerged[] = iaStream.flatMapToInt(iArray -> Arrays.stream(iArray)).toArray()
  14. /*
  15. The elements of the stream are
  16. of type int[] .
  17. For each element of the stream ,
  18. create a stream backed by
  19. this element using the
  20. Arrays.stream method.
  21. The created stream will be of
  22. type int .
  23. This is why the flatMapToInt
  24. method was used .
  25. This will flat and map each
  26. element of the type int[]
  27. of the Stream referenced by
  28. iaStream into elements of
  29. the type int , creating
  30. an IntStream .
  31. Collect the elements of the
  32. IntStream into an array .
  33. array . */
  34. iaMerged ==> [ 1, 2, 3, 1, 5, 9 ]
  35.  
  36.  
  37. > Stream <int [][]> iaaStream = Stream.of(new int[][] { { 1, 2, 3 } , { 4, 5, 6 } }, new int[][]{ {5, 9 , 12 } })
  38. /*
  39. Using the Stream.of method create
  40. a sequential order Stream
  41. whose elements are of type
  42. int[][] .*/
  43. iaaStream ==> java.util.stream.ReferencePipeline$Head@6767c1fc
  44.  
  45. > int iaaMerged[][] = iaaStream.flatMap(iaaElement -> Arrays.stream(iaaElement)).toArray(int[][]::new)
  46. /*
  47. For each element of the stream ,
  48. apply the method Arrays.stream .
  49. This methods will return a stream
  50. which elements are of type
  51. int [] .
  52. The result of the flatMap function
  53. is a Stream of objects .
  54. Using the toArray method , collect
  55. the elements of the flat mapped
  56. stream of objects , into an array
  57. of type int[][] .*/
  58. iaaMerged ==> [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 5, 9, 12 ] ]

9- Sorting arrays

The java.util.Arrays class provides some utility methods to manipulate arrays .

The Arrays.parallelSort method can be used to sort arrays in parallel . If the number of elements of the array to be sorted is less then a specified threshold the Arrays.parallelSort will sort the arrays elements using the Arrays.sort method .

For arrays of primitive types , Arrays.parallelSort and Arrays.sort will sort the element in ascending order.

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5.  
  6. > int[] iArray = { 4, 1, 7, 8, 3 };
  7. iArray ==> [ 4, 1, 7, 8, 3 ]
  8.  
  9. > Arrays.sort(iArray)
  10.  
  11. > iArray
  12. iArray ==> [ 1, 3, 4, 7, 8 ]
  13.  
  14.  
  15. > double[] dArray = {10 , 12 , 14 , 5.0 , 1/3.0}
  16.  
  17. > Arrays.parallelSort(dArray)
  18.  
  19. > dArray
  20. dArray ==> [ 0.3333333333333333, 5.0, 10.0, 12.0, 14.0 ]
  21.  
  22.  
  23. > char cArray[] = { 'a' , 'e' , 'i' , 'o' , 'u' , 'z' , 'h' , 'r' , 'v' }
  24.  
  25. > Arrays.sort(cArray , 5 , 9)
  26. /*
  27. Sort cArray only from index 5
  28. inclusive , till index 9 not
  29. inclusive .*/
  30.  
  31. > cArray
  32. cArray ==> [ 'a', 'e', 'i', 'o', 'u', 'h', 'r', 'v', 'z' ]
  33.  
  34. > Arrays.parallelSort(cArray , 1 , 9)
  35. /*
  36. Parallel sort cArray from
  37. index 1 inclusive , till
  38. index 9 not inclusive .*/
  39.  
  40. > cArray
  41. cArray ==> [ 'a', 'e', 'h', 'i', 'o', 'r', 'u', 'v', 'z' ]
  42.  
  43.  
  44. > int iArrayOne [][] = { { 4, 2 }, { 1, 0 } }
  45. iArrayOne ==> [ [4, 2 ], [ 1, 0 ] ]
  46.  
  47. > for ( int i = 0 ; i < iArrayOne.length ; i++ )
  48. Arrays.parallelSort(iArrayOne[i]);
  49.  
  50. > iArrayOne
  51. iArrayOne ==> [ [ 2, 4 ], [ 0, 1 ] ]
  52.  
  53.  
  54. > int iArrayTwo [][][] = { { { 4, 2 }, { 1, 0 } } };
  55. iArrayTwo ==> [ [ [ 4, 2 ], [ 1, 0 ] ] ]
  56.  
  57. > for (int i = 0 ; i < iArrayTwo.length ; i++ )
  58. for(int j = 0 ; j < iArrayTwo[i].length ; j++ )
  59. Arrays.parallelSort(iArrayTwo[i][j]);
  60.  
  61. > iArrayTwo
  62. iArrayTwo ==> [ [ [ 2, 4 ], [ 0, 1 ] ] ]

For arrays of reference type , if the type implements the Comparable interface , then these methods will use the compareTo method of the Comparable interface to sort the array . This is called the natural ordering , and the compareTo method is called the natural comparison method .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > String sArray[] = { "ab", "aa", "ae" }
  6. sArray ==> [ "ab", "aa", "ae" ]
  7.  
  8. > Arrays.parallelSort(sArray)
  9. /*
  10. The String class implements the comparable
  11. interface as such it is possible
  12. to use either of Arrays.parallelSort
  13. or Arrays.sort to sort an array of
  14. Strings .*/
  15.  
  16. > sArray
  17. sArray ==> String[3] { "aa", "ab", "ae" }
  18.  
  19.  
  20. > Object oArray[] = { new Object(), new Object() }
  21. oArray ==> [ java.lang.Object@5e5792a0, java.lang.Object@26653222 ]
  22.  
  23. > Arrays.sort(oArray)
  24. /*
  25. The Object class does not implement
  26. the Comparable interface , as such ,
  27. an array of Objects cannot be sorted
  28. using Arrays.sort or Arrays.parallelSort .*/
  29. | Exception java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.Comparable (java.lang.Object and java.lang.Comparable are in module java.base of loader 'bootstrap')
  30. | at ComparableTimSort.countRunAndMakeAscending (ComparableTimSort.java:320)
  31. | at ComparableTimSort.sort (ComparableTimSort.java:188)
  32. | at Arrays.sort (Arrays.java:1249)
  33. | at (#6:1)
  34.  
  35.  
  36. > /*
  37. Create a class File
  38. which implements the Comparable
  39. interface .*/
  40. class File implements Comparable<File>
  41. {
  42. String fileName;
  43. public File(String fileName)
  44. {
  45. this.fileName = fileName ;
  46. }
  47. @Override
  48. public int compareTo(File file)
  49. {
  50. return this.fileName.compareTo(file.fileName);
  51. }
  52. }
  53.  
  54. > File files[] = { new File("Manager.java"), new File("File.java") }
  55. files ==> [ File@4b9e13df, File@2b98378d ]
  56.  
  57. > System.out.println( "[ " + files[0].fileName + " , " + files[1].fileName + " ]");
  58. [ Manager.java , File.java ]
  59.  
  60. > Arrays.parallelSort(files , 0 , 2 )
  61.  
  62. > System.out.println( "[ " + files[0].fileName + " , " + files[1].fileName + " ]");
  63. [ File.java , Manager.java ]

If a type does not implement the Comparable interface , then the Arrays.parallelSort and Arrays.sort , can be passed a Comparator to sort the arrays .

  1. jshell>
  2.  
  3. > import java.util.Arrays ;
  4.  
  5. > Object oArray[] = { new Object(), new Object() }
  6. oArray ==> [ java.lang.Object@735b5592, java.lang.Object@58651fd0 ]
  7.  
  8. > Arrays.parallelSort(oArray , 0 , 2 , new Comparator<Object>(){
  9. @Override
  10. public int compare(Object objectOne , Object objectTwo)
  11. {
  12. return objectOne.toString().compareTo(objectTwo.toString());
  13. }
  14. });
  15. /*
  16. Sort the array by passing a
  17. Comparator which sort by
  18. the String value of Object .*/
  19.  
  20. > oArray
  21. oArray ==> [ java.lang.Object@58651fd0, java.lang.Object@735b5592 ]
  22.  
  23.  
  24. > /*
  25. Create a Class Point
  26. which does not implement
  27. Comparable .*/
  28. class Point
  29. {
  30. String axis ;
  31. int position ;
  32. public Point(String axis , int position)
  33. {
  34. this.axis = axis;
  35. this.position = position;
  36. }
  37.  
  38. public String getAxis()
  39. {
  40. return this.axis;
  41. }
  42.  
  43. public int getPosition()
  44. {
  45. return this.position;
  46. }
  47.  
  48. public String toString()
  49. {
  50. return this.axis + ":" + position ;
  51. }
  52. }
  53.  
  54.  
  55. > Point points[] = { new Point("y",10), new Point("x",5), new Point("y" ,1), new Point("z" , 4) }
  56. /*
  57. Create an array of points .*/
  58. points ==> [ y:10, x:5, y:1, z:4 ]
  59.  
  60. Comparator<Point> axisComparator = Comparator.comparing(Point::getAxis);
  61. /*
  62. The Comparator class has a static
  63. method comparing.
  64. It creates a Comparator using a
  65. Comparable value extracted by
  66. a function .
  67. In this case the Comparator created
  68. for the Point type is using
  69. the axis field which is a Comparable
  70. of type String .*/
  71.  
  72. > Arrays.sort( points , axisComparator )
  73. /*
  74. Sort the array using the Comparator :
  75. axisComparator .*/
  76.  
  77. > points
  78. points ==> [ x:5, y:10, y:1, z:4 ]
  79.  
  80. > Arrays.sort( points , axisComparator.reversed())
  81. /*
  82. The reversed method of Comparator
  83. returns a reverse Comparator .
  84. So the ordering will be
  85. reversed .*/
  86.  
  87. > points
  88. points ==> [ z:4.0, y:10.0, y:1.0, x:5.0 ]
  89.  
  90. > Comparator<Point> axisPositionComparator = Comparator.comparing(Point::getAxis).thenComparing(Point::getPosition);
  91. /*
  92. Create a Comparator which first
  93. compares using the axis field ,
  94. and when the values are equal
  95. compare using the position field .*/
  96.  
  97. > Arrays.parallelSort(points , axisPositionComparator );
  98.  
  99. > points
  100. points ==> [ x:5, y:1, y:10, z:4 ]
  101.  
  102. > Arrays.parallelSort(points , ( point1 , point2 ) -> point1.position - point2.position ) ;
  103. /*
  104. Use lambda expression , to pass
  105. the compare method of Comparator .*/
  106.  
  107. > points
  108. points ==> [ y:1, z:4, x:5, y:10 ]

The Stream API can also be used to create a sorted shallow copy of the array .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > int iArray[] = { 10, 3, 5 }
  6. /*
  7. Create an array of type
  8. int[] , and store a
  9. reference to it in the
  10. variable iArray .*/
  11. iArray ==> int[3] { 10, 3, 5 }
  12.  
  13. > int iArrayCopySorted [] = Arrays.stream(iArray).sorted().toArray()
  14. /*
  15. Use Arrays.stream to create a
  16. sequential IntStream , with
  17. its source being the
  18. array referenced by the
  19. variable iArray .
  20. Using the sorted function ,
  21. create a sorted stream ,
  22. using primitive types
  23. comparaison .
  24. Use toArray method to create
  25. an array of type int[]
  26. from the sorted IntStream
  27. Store a reference to the
  28. created array in the
  29. variable iArrayCopySorted .*/
  30. iArrayCopySorted ==> int[3] { 3, 5, 10 }
  31.  
  32.  
  33. > String sArray[] = {"ar" , "ab"}
  34. /*
  35. Create an array of type
  36. String[] and store a
  37. reference to it in the
  38. variable sArray .*/
  39. sArray ==> String[2] { "ar", "ab" }
  40.  
  41. > String sArrayCopySorted[] = Arrays.stream(sArray).sorted().toArray(String[]::new)
  42. /*
  43. Using Arrays.stream , create a
  44. stream backed by the array
  45. referenced by sArray .
  46. Using the sorted method , sort
  47. the String elements . String
  48. implements the Comparable
  49. interface . As such sort using
  50. the compareTo method .
  51. The sorted method returns a
  52. sorted Stream of Objects .
  53. Using the toArray method , create
  54. an array from the elements of the
  55. sorted Stream .
  56. Pass to the toArray , method the
  57. function which will create the
  58. array of the given type , and
  59. the passed size to the
  60. function
  61. Store a reference to the sorted
  62. array in the sArrayCopySorted
  63. variable .*/
  64. sArrayCopySorted ==> [ "ab", "ar" ]
  65.  
  66.  
  67. > int iaa[][] = { { 4, 3 }, { 2, 1 } }
  68. /*
  69. Create an array of type int[][] ,
  70. and store a reference to it
  71. in iaa .*/
  72.  
  73. > int iaaShallowCopySorted[][] = Arrays.
  74. stream(iaa).
  75. sorted(
  76. (ia1 , ia2)->
  77. {
  78. Arrays.parallelSort(ia1);
  79. Arrays.parallelSort(ia2);
  80. return ia1[0] - ia2[0];
  81. }).
  82. toArray(int[][]::new);
  83. /*
  84. Use Arrays.stream to create a
  85. sequential stream backed by
  86. the array referenced by the
  87. variable iaa.
  88. The elements of the stream are
  89. of type int[] , and they don't
  90. implement the Comparable interface .
  91. As such we can pass to the sorted
  92. function a comparator , to be used
  93. for performing comparison between
  94. elements .
  95. The comparator is passed as a lambda
  96. function .
  97. The lambda function takes , two variables
  98. of type int[] . Using Arrays.parallelSort
  99. it sorts , the arrays , and finally to
  100. compare the two arrays , it compare
  101. the first element of the two arrays ,
  102. by subtracting them .
  103. The sorted function return a sorted
  104. stream of objects .
  105. Use the toArray method , to create
  106. an array of type int[][] , from
  107. this sorted stream .
  108. Store a reference of the newly
  109. created array in the variable
  110. iaaShallowCopySorted .*/
  111. iaaShallowCopySorted ==> [ [ 1, 2 ], [ 3, 4 ] ]
  112. /*
  113. iaaShallowCopySorted[0] is sorted.
  114. iaaShallowCopySorted[1] is sorted.
  115. The array referenced by iaaShallowCopySorted
  116. is sorted .*/
  117.  
  118. > iaa
  119. /*
  120. iaa[0] is sorted .
  121. iaa[1] is sorted .
  122. The array referenced by iaa is
  123. not sorted .*/
  124. iaa ==> [ [ 3, 4 ], [ 1, 2 ] ]

10- Searching for an element in an Array

If an array is sorted , the java.util.Arrays.binarySearch method can be used to search the array for a given element .

The Arrays.binarySearch method returns the index of the element if it is found . If not found it will return (-(insertion point) - 1) . So to get where the not found element must be inserted in the array , just negate the return value and subtract 1 .

If multiple elements match the elements to search for , there is no guarantee which matching element index is returned .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > int iArray[] = { 0, 1, 2 }
  6. /*
  7. iArray is a variable of type
  8. int[] which holds a reference
  9. to a sorted Array .*/
  10.  
  11. > Arrays.binarySearch(iArray , -1)
  12. /*
  13. Search for the element -1
  14. in the sorted array .
  15. The element -1 is not found.
  16. -1 is less than 0 , so it must
  17. be inserted at index 0 , As such
  18. the binary search method returns
  19. minus the insert position minus 1 ,
  20. which is : -0 -1 , which is -1 .
  21. To get where the element will be
  22. inserted from the value returned
  23. by Arrays.binarySearch , negate
  24. the value and substract 1 . In this
  25. case --1 -1 = 1 -1 = 0 .*/
  26. -1
  27.  
  28.  
  29. > Arrays.binarySearch(iArray , 10)
  30. /*
  31. 10 is not found in the sorted
  32. array , the binarySearch method
  33. return minus the insert position
  34. of 10 minus 1.
  35. 10 if it is to be inserted must be
  36. inserted as the last element . As
  37. such binarySearch return -3 -1
  38. which is -4 .*/
  39. -4
  40.  
  41. > Arrays.binarySearch(iArray , 0 , 1 , 0)
  42. /*
  43. Search the array from index 0 inclusive ,
  44. to index 1 not inclusive , for the
  45. integer 0 .
  46. The integer 0 is found in the array ,
  47. and this is the first element .*/
  48. 0
  49.  
  50.  
  51. >int iArrayOne [][] = { { 2, 4 } , { 0, 1 } } ;
  52. /*
  53. iArrayOne holds a reference to an
  54. array of length 2 which its elements
  55. are of type int [] . Each element of
  56. type int[] is sorted .*/
  57.  
  58. > int ElementToSearchFor = 0 ;
  59. /*
  60. The element to search for is 0 .*/
  61.  
  62. > /*
  63. Loop through the elements of the array
  64. referenced by the variable iArrayOne .
  65. The elements of the array are of type
  66. int[] .
  67. Each type int [] element is sorted ,
  68. search it using Arrays.binarySearch .
  69. Print the index of the array where
  70. the element is found , and the index
  71. of the element in the array .*/
  72. for ( int i = 0 ; i < iArrayOne.length ; i++ )
  73. {
  74. int indexFoundElement = Arrays.binarySearch(iArrayOne[i] , ElementToSearchFor) ;
  75. if( indexFoundElement >= 0 ){
  76. System.out.println("Found at : [" + i + "]" + "[" + indexFoundElement + "]");
  77. break;
  78. }
  79. }
  80. Found at : [1][0]

When searching arrays which are not of the primitive types using the Arrays.binarySearch , the array elements type must implement the Comparable interface , or if not , a Comparator must be passed to Arrays.binarySearch .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > String sArray[] = { "ea", "ca", "ba" };
  6. sArray ==> [ "ea", "ca", "ba" ]
  7.  
  8. > Arrays.parallelSort(sArray)
  9. /*
  10. sArray is not sorted , to search
  11. an array using Arrays.binarySearch
  12. it must be sorted . As such sort the
  13. array using Arrays.parallelSort .
  14. If we don't want to sort the array ,
  15. a copy of it can be created and
  16. searched .*/
  17. sArray ==> [ "ba", "ca", "ea" ]
  18.  
  19. > Arrays.binarySearch(sArray , 1 , 3 , "ca")
  20. /*
  21. Search the array from index
  22. 1 till index 3 , for the
  23. element "ca" .
  24. String type implements the
  25. Comparable interface , as
  26. such the binarySearch method
  27. can be used .
  28. An element containing a
  29. reference to "ca" was
  30. found at index 1
  31. of the array .
  32. If String did not implement the
  33. Comparable interface a
  34. java.lang.ClassCastException
  35. would have been thrown .*/
  36. 1
  37.  
  38. >/* Create class Seconds */
  39. class Seconds
  40. {
  41. int seconds ;
  42. public Seconds(int seconds)
  43. {
  44. this.seconds = seconds;
  45. }
  46. }
  47.  
  48. > Seconds time[] = { new Seconds(10), new Seconds(20) }
  49. /*
  50. The array containing Seconds(10)
  51. and Seconds(20) is sorted by
  52. seconds , since 10 < 20 .*/
  53. time ==> [ Seconds@58651fd0, Seconds@4520ebad ]
  54.  
  55. > System.out.println( "[ " + time[0].seconds + " , " + time[1].seconds + " ]");
  56. /*output*/
  57. [ 10 , 20 ]
  58.  
  59. > Arrays.binarySearch( time , 0 , 2 , new Seconds(20) , new Comparator<Seconds>(){
  60. @Override
  61. public int compare(Seconds secondsOne , Seconds secondsTwo)
  62. {
  63. return secondsOne.seconds - secondsTwo.seconds ;
  64. }});
  65. /*
  66. Use Arrays.binarySearch method
  67. to search an array from
  68. start index 0 inclusive , till
  69. index 2 exclusive .
  70. The element to search for is :
  71. new Seconds(20) .
  72. A Comparator was created to
  73. compare the values of the
  74. elements of the array by the
  75. seconds field .*/
  76. 1

If the elements of the array are not sorted , we can loop over the array and compare each element individually , and just return the index.

  1. jshelh>
  2.  
  3. > /*Class IndexSearch*/
  4. class IndexSearch
  5. {
  6. public static int findByIndex (int[] iArray , int iElement)
  7. {
  8. /* Method for primitive type int
  9. * Returns the index of the element to search for .
  10. * -1 if not found .*/
  11. for(int i = 0 ; i < iArray.length ; i++)
  12. {
  13. if(iArray[i] == iElement )
  14. /* element found return its index .*/
  15. return i;
  16. }
  17. return -1 ;
  18. }
  19.  
  20.  
  21. public static <T extends Comparable<? super T>> int findByIndex (T[] cArray , T element)
  22. {
  23. /* Method for types which implement the Comparable interface
  24. * Returns the index of the element to search for .
  25. * -1 if not found .*/
  26. for(int i = 0 ; i < cArray.length ; i++)
  27. {
  28. if(cArray[i].compareTo(element) == 0 )
  29. /* element found return its index .*/
  30. return i;
  31. }
  32. return -1 ;
  33. }
  34.  
  35. public static <T> int findByIndex(T[] ncArray , T element , Comparator<? super T> comparator)
  36. /* Method For types that do not implement Comparable interface .
  37. * As such they must provide a Comparator .
  38. * Returns the index of the element to search for .
  39. * -1 if not found .*/
  40. {
  41. for(int i = 0 ; i < ncArray.length ; i++)
  42. {
  43. if(comparator.compare(ncArray[i] , element) == 0 )
  44. /* element found return its index .*/
  45. return i;
  46. }
  47. return -1 ;
  48. }
  49. }
  50.  
  51. > int iArray[] = { 10, 0, 22, 11 }
  52. /*
  53. Create an array which has
  54. a type of int[] , and which
  55. is not sorted .
  56. Store a reference to it in
  57. the variable iArray .*/
  58. iArray ==> [ 10, 0, 22, 11 ]
  59.  
  60. > IndexSearch.findByIndex(iArray , 22)
  61. /*
  62. Search the array for the
  63. element 22 .
  64. The element 22 is found at
  65. index 2 .*/
  66. 2
  67.  
  68. > String sArray[] = { "ce", "af", "ah" }
  69. /*
  70. Create an array of type
  71. String[] which is not
  72. sorted .*/
  73. sArray ==> [ "ce", "af", "ah" ]
  74.  
  75. > IndexSearch.findByIndex(sArray , "af")
  76. /*
  77. Search the array for the element
  78. "af".
  79. The String type implements the
  80. Comparable interface , as such
  81. the Comparable findByIndex
  82. method is called .
  83. The element of the array containing
  84. a reference to a String of value
  85. "af" is found at index 1 .*/
  86. 1
  87.  
  88. > Object object = new Object() ;
  89. /*
  90. Create a new Object .*/
  91. object ==> java.lang.Object@20e2cbe0
  92.  
  93. > Object oArray[] = { new Object() , object };
  94. /*
  95. Create an array of two
  96. objects .*/
  97. oArray ==> Object[2] { java.lang.Object@68be2bc2, java.lang.Object@20e2cbe0 }
  98.  
  99. > IndexSearch.findByIndex(oArray , object , Comparator.comparing(Object::toString))
  100. /*
  101. Search the array for an object .
  102. Object does not implement the
  103. Comparable interface .
  104. Create a Comparator using the
  105. Comparator.comparing method from
  106. the Object toString method .
  107. IndexSearch.findByIndex comparator
  108. method is called .
  109. A reference to the object searched
  110. for is found at index 1 .*/
  111. 1

The Stream API , can be used to check for the existence of an element in an array , and to return the element , but it cannot be used to get the index of the element in a straight forward manner .

The Stream anyMatch method can be used to check if an element in the array verifies certain conditions , like for example equality , larger or equal , or anything else.

  1. jshelh>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > int iArray[] = { 10, 2, 15 }
  6. /*
  7. Create an array of type int[] ,
  8. and store a reference to it
  9. in iArray .*/
  10. iArray ==> [ 10, 2, 15 ]
  11.  
  12. > Arrays.stream(iArray).anyMatch(iElem -> iElem == 2 );
  13. /*
  14. Using Arrays.stream create a
  15. sequential stream backed
  16. by the array referenced by
  17. the variable iArray.
  18. Using the anyMatch method ,
  19. pass a lambda function ,
  20. to test if any element
  21. is equal to 2 .*/
  22. $ ==> true
  23.  
  24. > import java.util.function.Predicate;
  25. /*
  26. A predicate is a functional
  27. interface , it can be assigned
  28. a lambda function .
  29. A predicate can be combined
  30. with another predicate using
  31. the and , or methods .
  32. It can be negated using the
  33. negate method .
  34. A predicate is used to test for
  35. a condition .*/
  36.  
  37. > import java.util.function.IntPredicate;
  38.  
  39. > IntPredicate lessTwenty = iElem -> iElem < 20 ;
  40. /*
  41. Create a predicate which will test ,
  42. if the passed integer element
  43. is less than 20 .
  44. */
  45. lessTwenty ==> $Lambda$15/0x000000102faa9440@4520ebad
  46.  
  47. > IntPredicate lessTwentyAndLargerFourteen = lessTwenty.and( iElem -> iElem > 14 )
  48. /*
  49. Create a predicate , which will test
  50. if an element is less than twenty ,
  51. and larger than 14 .*/
  52. lessTwentyAndLargerFourteen ==> java.util.function.Predicate$$Lambda$17/0x000000102faaa840@548a9f61
  53.  
  54. > Arrays.stream(iArray).anyMatch(lessTwentyAndLargerFourteen)
  55. /*
  56. Use Arrays.stream , to create
  57. a sequential Stream backed by
  58. the array referenced by the
  59. variable iArray .
  60. Use anyMatch with the predicate
  61. lessTwentyAndLargerFourteen , to
  62. test if any element is larger than
  63. fourteen and less than twenty .*/
  64. $ ==> true
  65.  
  66.  
  67. > String[][] sArray = { { "ab", "ar" }, {"iq", "id" } }
  68. /*
  69. Create an array of type String[][] ,
  70. and store a reference to it in ,
  71. the variable sArray .*/
  72. sArray ==> [ [ "ab", "ar" ], [ "iq", "id" ] ]
  73.  
  74. > Predicate<String[]> isNull = saElem -> saElem == null ;
  75. /*
  76. Create a lambda function which takes
  77. an element of type String[] , and
  78. check if its null .
  79. Store a reference to it , in the
  80. variable isNull .*/
  81. isNull ==> $Lambda$28/0x000000102faad040@57baeedf
  82.  
  83. > Arrays.stream(sArray).anyMatch(isNull)
  84. /*
  85. Use Arrays.stream method to create
  86. a sequential stream , backed by
  87. the array referenced by sArray.
  88. Use the anymatch method to check , if
  89. any element , is null , by passing
  90. the predicate isNull .*/
  91. $ ==> false
  92.  
  93. > Arrays.stream(sArray).anyMatch(isNull.negate())
  94. /*
  95. Use Arrays.stream method to
  96. create a sequential stream ,
  97. backed by the array
  98. referenced by sArray.
  99. Use the anymatch method to
  100. check , if any element ,
  101. is not null , by passing
  102. the negation of the
  103. predicate isNull .*/
  104. $ ==> true

The Stream filter method can be used to get a stream which elements satisfies certain predicates .

An array can be constructed from the filtered stream using the Stream toArray method .

A stream truncated to a certain number of elements , can be created from the filtered Stream using the Stream limit method .

An optional can be returned from the filtered Stream using the Stream findAny or findFirst methods .

The findFirst method , will return the first element of a Stream if the Stream has an encounter order , or any element if the stream does not have an encounter order .

The findAny will return any element of a Stream .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > int iArray[] = { 1, 2, 10, 2 }
  6. /*
  7. Create an array of type int[] ,
  8. store a reference to it , in
  9. the variable iArray .*/
  10.  
  11. > Arrays.stream(iArray).filter( iElem -> iElem == 2 ).toArray()
  12. /*
  13. Use Arrays.stream to create a
  14. sequential Stream backed
  15. by the array referenced by
  16. iArray .
  17. Using the filter method , pass
  18. a predicate which create a
  19. stream whose elements are
  20. filtered to be equal to 2 .
  21. Using the toArray method , convert
  22. the filtered Stream to an int [] .*/
  23. [ 2 , 2 ]
  24.  
  25. > Arrays.stream(iArray).filter( iElem -> iElem != 2 ).limit(1).toArray()
  26. /*
  27. Use Arrays.stream to create a
  28. sequential Stream backed
  29. by the array referenced by
  30. iArray .
  31. Using filter method , pass a predicate ,
  32. which create a stream containing
  33. elements different than
  34. 2 .
  35. Using limit method , create a Stream
  36. from the filtered Stream truncated
  37. to length 1 .
  38. Using the toArray method , create an
  39. array of type int[] .*/
  40. [ 1 ]
  41.  
  42. > Arrays.stream(iArray).filter( iElem -> iElem > 1 ).findFirst()
  43. /*
  44. Use Arrays.stream to create a
  45. sequential Stream backed
  46. by the array referenced by
  47. iArray .
  48. Use filter method , to create a
  49. Stream containing elements
  50. larger than 1 .
  51. Use findFirst to return an
  52. optional , containing the
  53. first element in the Stream ,
  54. if the Stream has an encounter
  55. order , or any element if
  56. not .*/
  57. $ ==> OptionalInt[2]
  58.  
  59. > Arrays.stream(iArray).filter( iElem -> iElem > 1 ).findAny()
  60. $ ==> OptionalInt[2]
  61. /*
  62. Use Arrays.stream to create a
  63. sequential Stream backed
  64. by the array referenced by
  65. iArray .
  66. Use filter method , to create a
  67. Stream containing elements
  68. larger than 1 .
  69. Use findAny to return an optional ,
  70. containing any element in the
  71. Stream .*/
  72. $ ==> OptionalInt[2]
  73.  
  74.  
  75.  
  76. > int iArray[][] = { { 1, 2 }, null, { } }
  77. /*
  78. Create an array of type int [][] ,
  79. and store a reference to it ,
  80. in the variable iArray. */
  81. [ [ 1 , 2 ], null, [ ] ]
  82.  
  83. > Predicate<int []> isNull = iaElem -> iaElem == null ;
  84. /*
  85. Create a lambda function , which
  86. checks , if its parameter of
  87. type int [] is null .*/
  88. isNull ==> $Lambda$15/0x000000102faa9440@5419f379
  89.  
  90. > Predicate<int []> isNullOrEmpty = isNull.or( iaElem -> iaElem.length == 0 )
  91. /*
  92. Create a Predicate which check if its
  93. parameter of type int[] is null or
  94. if it has a length of 0 .*/
  95. isNullOrEmpty ==> java.util.function.Predicate$$Lambda$17/0x000000102faaa840@1753acfe
  96.  
  97. > Arrays.stream(iArray).filter(isNullOrEmpty.negate()).findAny()
  98. /*
  99. Use Arrays.stream to create a
  100. sequential Stream backed
  101. by the array referenced by
  102. iArray .
  103. Use the filter method , to
  104. create a Stream which elements
  105. are neither null nor arrays
  106. which have a length of 0 .
  107. use findAny method to return ,
  108. the first found element , if
  109. the stream has an encounter
  110. order , or any element if
  111. not .*/
  112. $10 ==> Optional[[I@6093dd95]

11- Checking for arrays equality

The == operator can be used to check if two variables refers to the same array .

  1. jshell>
  2.  
  3. > int iArray[] = { 1, 2, 3 } , iArrayTwo[] , iArrayThree[] ;
  4. /*
  5. Create an array of type
  6. int[] , having the three
  7. elements 1 , 2 and 3 .
  8. Store a reference to it ,
  9. in the variable iArray .
  10. The variable iArrayTwo
  11. and iArrayThree holds
  12. no reference to any
  13. array of type int[] ,
  14. as such they refer
  15. to null .*/
  16. iArray ==> int[3] { 1, 2, 3 }
  17. iArrayTwo ==> null
  18. iArrayThree ==> null
  19.  
  20. > iArrayThree == iArrayTwo
  21. /*
  22. The variable iArrayThree and
  23. iArrayTwo are both of type
  24. int [] , and they both hold
  25. no reference to any array
  26. of type int[] , as such they
  27. both refers to null .*/
  28. $ ==> true
  29.  
  30. > iArray == iArrayTwo
  31. /*
  32. Compare the reference held
  33. by the variable iArray ,
  34. and the reference held
  35. by the variable iArrayTwo
  36. for equality .*/
  37. $ ==> false
  38.  
  39. > iArrayTwo = iArray
  40. /*
  41. Assign the reference held by the
  42. variable iArray , to the
  43. variable iArrayTwo. */
  44.  
  45. > iArray == iArrayTwo
  46. /*
  47. Compare the reference held by
  48. the variable iArray , to the
  49. reference held by the variable
  50. iArrayTwo for equality */
  51. $ ==> true

The Arrays.equals and Arrays.deepEquals methods can be used to compare two arrays for equality .

The Arrays.equals , will first check if the two passed variables refer to the same arrays , if so , they are equal . If not , and if any refers to null while the other is not null , it will return false . If not , if their length is different , it will return false . Finally it will compare the elements of the arrays using the == operator . If all the elements are deemed equal by ==, then Arrays.equals return true .

  1. jshell>
  2.  
  3. > int iArrayOne[] = { 1, 2, 3 } , iArrayTwo[] = { 1, 2, 4 } ;
  4. /*
  5. Create an array of type int [] ,
  6. formed from the elements : 1 ,
  7. 2 and 3 , and store a reference
  8. to it in the variable
  9. iArrayOne .
  10. Create an array of type int[] ,
  11. containing the elements : 1 , 2
  12. , 4 , and hold a reference to it
  13. in the variable iArrayTwo .*/
  14. iArrayOne ==> { 1, 2, 3 }
  15. iArrayTwo ==> { 1, 2, 4 }
  16.  
  17. > Arrays.equals( iArrayOne , iArrayTwo )
  18. /*
  19. iArrayOne != iArrayTwo
  20. iArrayOne and iArrayTwo are both
  21. not null .
  22. iArrayOne and iArrayTwo have the same
  23. length .
  24. Compare the elements of both arrays ,
  25. using the == operator .
  26. 1 == 1 , 2 == 2 , 3 != 4 .*/
  27. $ ==> false

The Arrays.deepEquals method will first check if the two passed variables are equal using the == operator .

Next if the variables are not equal using the == operator , and if any is null , it will return false .

If neither variables holds a reference to null , but if the arrays referred by these variables have different length , this method return false .

Next this method will loop through the two arrays , comparing the elements in order .

Two elements are equal if either using the== return true , or if they are both not arrays and using the element from the first array equals method , passing the element from the second array , returns true , or if they are both arrays of objects , and recursively calling the deepEquals method on these two elements return true , or if they are arrays of the primitive types and calling the Arrays.equals method on these two elements return true .

  1. jshell>
  2.  
  3. > int iArray[] = { 1, 2 };
  4. /*
  5. Create an array of type int
  6. [] , containing the elements
  7. 1 and 2 , and store a reference
  8. to it in the variable
  9. iArray .*/
  10. iArray ==> [ 1, 2 ]
  11.  
  12. > int iArrayTwo[][] = { iArray , iArray } ;
  13. /*
  14. Create an array of type int[][] ,
  15. stores inside it two references
  16. to the array referenced by
  17. the iArray variable .*/
  18. iArrayTwo ==> [ [ 1, 2 ], [ 1, 2 ] ]
  19.  
  20. > int iArrayThree[][] = { iArray , { 1, 2 } }
  21. /*
  22. Create an array of type int[][] ,
  23. store a reference inside it to the
  24. array referenced by the variable
  25. iArray .
  26. Create another array of type int[] ,
  27. containing the values 1 and 2 ,
  28. and store a reference to it
  29. inside the array referenced by
  30. iArrayThree .*/
  31. iArrayThree ==> [ [ 1, 2 ], [ 1, 2 ] ]
  32.  
  33. > Arrays.equals(iArrayTwo , iArrayThree)
  34. /*
  35. iArrayTwo != iArrayThree .
  36. iArrayTwo and iArrayThree are
  37. both not null .
  38. iArrayTwo and iArrayThree have
  39. equal length .
  40. Compare the elements of both
  41. arrays in order .
  42. iArrayTwo[0] == iArrayThree[0]
  43. iArrayTwo[1] != iArrayThree[1] .*/
  44. $ ==> false
  45.  
  46.  
  47. > Arrays.deepEquals(iArrayTwo , iArrayThree)
  48. /*
  49. iArrayTwo != iArrayThree .
  50. iArrayTwo and iArrayThree are
  51. both not null .
  52. iArrayTwo and iArrayThree have
  53. equal length .
  54. Compare the elements of both
  55. arrays in order .
  56. iArrayTwo[0] == iArrayThree[0]
  57. iArrayTwo[1] != iArrayThree[1]
  58. Both iArrayTwo[1] and iArrayThree[1]
  59. are not null .
  60. Both iArrayTwo[1] and iArrayThree[1]
  61. are of type int[] .
  62. Use Arrays.equals(iArrayTwo[1] , iArrayThree[1] )
  63. iArrayTwo[1] != iArrayThree[1] .
  64. iArrayTwo[1] and iArrayThree[1] are
  65. both not null .
  66. iArrayTwo[1] and iArrayThree[1] have
  67. equal length .
  68. Compare the elements of both
  69. iArrayTwo[1] and iArrayThree[1]
  70. in order .
  71. iArrayTwo[1][0] == iArrayThree[1][0]
  72. iArrayTwo[1][1] == iArrayThree[1][1] .*/
  73. $ ==> true

12- Filling an array

The Arrays.fill method , can be used to fill a part of an array , or a whole array , using a provided single value .

  1. jshell>
  2.  
  3. > import java.util.Arrays ;
  4.  
  5. > int iArray[] = new int[3];
  6. /*
  7. Create an array of type int[]
  8. , having a length of
  9. three .
  10. The array is of type int[] , as
  11. such all of its elements are
  12. initialized to the default
  13. value of 0 .
  14. Store a reference to the
  15. newly created array in the
  16. variable iArray .*/
  17. iArray ==> [ 0, 0, 0 ]
  18.  
  19. > Arrays.fill(iArray , 1 , 3 , 1 )
  20. /*
  21. Fill the elements of
  22. the array referenced by
  23. the variable iArray ,
  24. starting index 1 inclusive ,
  25. till index 3 exclusive ,
  26. with the value 1 .*/
  27.  
  28. > iArray
  29. iArray ==> [ 0, 1, 1 ]
  30.  
  31.  
  32. > int iArrayOne[][] = new int[2][2]
  33. /*
  34. Create an array of length 2 ,
  35. which elements are of type
  36. int[] .
  37. Create two arrays of type
  38. int[] , each of length 2 ,
  39. which elements are initialized
  40. to 0 , and store a reference
  41. to them inside the array
  42. referenced by the variable
  43. iArrayOne .*/
  44. iArrayOne ==> [ [ 0, 0 ], [ 0, 0 ] ]
  45.  
  46. > Arrays.fill(iArrayOne , new int[]{1,0})
  47. /*
  48. Create an array of type int [] ,
  49. having the two elements 1 ,
  50. and 0 .
  51. Fill the elements of the array
  52. referenced by the variable
  53. iArrayOne , with a reference
  54. to the newly created array .*/
  55.  
  56. > iArrayOne
  57. iArrayOne ==> [ [ 1, 0 ], [ 1, 0 ] ]

13- Generating an array

The Arrays.parallelSetAll and Arrays.setAll methods can be used to fill all the elements of an array using a provided generator function . The generator functions receives the index of the element to be filled.

The difference between Arrays.parallelSetAll and Arrays.setAll is that in Arrays.parallelSetAll , the filling is done in parallel .

  1. jshell >
  2.  
  3. > import java.util.Arrays ;
  4.  
  5. > double dArray[] = new double[2] ;
  6. /*
  7. Create an array of type double[] ,
  8. which its elements are
  9. initialized to the default
  10. value of 0.0 .
  11. Store a reference to it in the
  12. variable dArray .*/
  13.  
  14. > Arrays.parallelSetAll( dArray, index -> Math.random() + index );
  15. /*
  16. Parallel set all the elements of
  17. the array referenced by the
  18. variable dArray using the
  19. parallelSetAll function .
  20. The parallelSetAll receives ,
  21. as a first argument , the
  22. array to be filled , and
  23. as a second argument , a
  24. function which receives the
  25. index of the element to be
  26. filled , and generates
  27. an element .*/
  28.  
  29. > dArray
  30. dArray ==> [ 0.5157471129598236, 1.1915950324664246 ]

The Stream API generate method can be used to generate a sequential unordered stream .

It receives as an argument a function which will perform generating the elements of the stream .

The generate method can be used with the limit method of the Stream API , to create a stream with the specified limit , and with the toArray method to create an array.

  1. jshell >
  2.  
  3. > import java.util.stream.Stream;
  4.  
  5. > Double dArray[] = Stream.generate(()->Math.random()).limit(2).toArray(Double[]::new);
  6. /*
  7. Pass to the Stream.generate method
  8. a lambda function , which
  9. returns a random double
  10. number .
  11. Using limit , create a stream with
  12. only 2 elements from the stream
  13. generated by generate .
  14. Using toArray , create an array
  15. out of the elements of this
  16. stream , passing a function which
  17. will create an array of a Double
  18. type , and of the length provided
  19. by toArray .*/
  20. dArray ==> [ 0.12407886170343518, 0.6000542329067424 ]

The Stream API iterate method can be used to generate a sequential ordered stream . It takes as an argument a seed , and a function , and it will produce the series seed , f(seed) , f(f(seed)) ... .

Using the limit method of Stream , a stream with a limited number of elements can be created from the stream generated by iterate , and using the Stream toArray method , an array can be created out of the limited Stream .

  1. jshell >
  2.  
  3. > import java.util.stream.Stream;
  4.  
  5. > Integer iArray [] = Stream.iterate( 1 , seed -> 2 * seed).limit(4).toArray(Integer[]::new);
  6. /*
  7. Create a Stream using the iterate
  8. method . The elements of the
  9. stream are 1 , 2 , 4 , 8... They
  10. are the seed and the computed values
  11. by the function passed to iterate
  12. which receives as argument ,
  13. the seed , f(seed) ...
  14. Create a stream of 4 elements using
  15. the limit method .
  16. Create an array from the elements
  17. of the limited Stream , passing
  18. to toArray , a function which
  19. will create an array of the
  20. Integer type , and of the length
  21. provided by toArray .*/
  22. iArray ==> [ 1, 2, 4, 8 ]

14- Finding the max and min elements of an array

If the array is sorted in ascending order, then the min element is the first element of the array , and the max element is the last element of the array .

If the array is not sorted , any of the looping mechanism can be used to search the array for the min and max value .

  1. > int iArray[] = { 1 , 2, 3 }
  2. /*
  3. Create an array of type int [] ,
  4. containing the three elements
  5. 1 , 2 and 3 .
  6. Store a reference to this array ,
  7. in the variable iArray .*/
  8. iArray ==> [ 1, 2, 3 ]
  9.  
  10. /*
  11. The array referenced by iArray ,
  12. is sorted in ascending order ,
  13. as such the min value is
  14. iArray[0] , and the max value
  15. is iArray[2] .*/
  16.  
  17.  
  18. > int iArray[] = { 3 , -1, 2 }
  19. /*
  20. Create an array of type int[] ,
  21. containing the elements 3 , -1
  22. and 2 .
  23. Store a reference to it inside
  24. the variable iArray .*/
  25. iArray ==> [ 3, -1, 2 ]
  26.  
  27. > int max = Integer.MIN_VALUE
  28. /*
  29. set max equal to
  30. Integer.MIN_VALUE .*/
  31. max ==> -2147483648
  32.  
  33. > int min = Integer.MAX_VALUE
  34. /*
  35. set min equal to
  36. Integer.MAX_VALUE .*/
  37. min ==> 2147483647
  38.  
  39. > for (int iElem : iArray)
  40. {
  41. if(iElem > max)
  42. max = iElem;
  43. if(iElem < min )
  44. min = iElem;
  45. }
  46. > max
  47. max ==> 3
  48.  
  49. > min
  50. min ==> -1

The Stream API max and min methods , can also be used for finding the max and min values .

  1. > import java.util.Arrays;
  2.  
  3. > int iArray[] = { 1, -1, 2 }
  4. /*
  5. Create an array of type int[] , and
  6. store a reference to it in
  7. the variable iArray .*/
  8.  
  9. > Arrays.stream(iArray).max()
  10. /*
  11. Use Arrays.stream method to
  12. get a sequential stream backed
  13. by the array referenced by
  14. iArray .
  15. Use the Stream max method to
  16. find the max element of the
  17. stream .
  18. The Stream max method returns
  19. an Optional .*/
  20. $ ==> OptionalInt[2]
  21.  
  22. > Arrays.stream(iArray).min()
  23. /*
  24. Use Arrays.stream method to
  25. create a sequential stream
  26. backed by the array referenced
  27. by iArray .
  28. Use the Stream method min ,
  29. to find the min value of the
  30. stream .
  31. The stream min method returns ,
  32. an Optional .*/
  33. $ ==> OptionalInt[-1]
  34.  
  35.  
  36. > String sArray[] = { "or" , "ei" }
  37. /*
  38. Create an array of type String[] ,
  39. containing two references
  40. to the Strings "or" , and
  41. "ei" .
  42. Store a reference of this array ,
  43. in the variable sArray .*/
  44.  
  45. > Arrays.stream(sArray).min((elem1 , elem2)-> elem1.compareTo(elem2))
  46. /*
  47. use Arrays.stream to create
  48. a sequential stream backed
  49. by the array referenced by
  50. sArray .
  51. The created stream is a stream of
  52. objects , as such we pass a
  53. Comparator to min , to perform
  54. the Comparison .
  55. The passed Comparator is a lambda
  56. function , which calls the compareTo
  57. method of elem1 .
  58. elem1 and elem2 , both have the
  59. compareTo method because the
  60. stream objects are of type
  61. String , and String implements
  62. the Comparable interface .*/
  63. $ ==> Optional[ei]
  64.  
  65. > Arrays.stream(sArray).max((elem1 , elem2)-> elem1.compareTo(elem2))
  66. /*
  67. Use Arrays.stream method to
  68. create a sequential stream
  69. backed by the array referenced
  70. by the variable sArray .
  71. The Stream is a stream of
  72. objects , as such pass a
  73. Comparator to the Stream max
  74. function .
  75. The comparator is an lambda
  76. function , which call elem1
  77. compareTo method .
  78. The max method returns an Optional .*/
  79. $ ==> Optional[or]

15- Finding the average , and the sum of an array

To find the average or the sum of an array , any of the looping methods can be used .

  1. jshell>
  2.  
  3. > int iArray[] = {-1, 0, 2 };
  4. /*
  5. Create an array of type
  6. int[] , and store a
  7. reference to it , in the
  8. variable iArray .*/
  9. iArray ==> [ -1, 0, 2 ]
  10.  
  11. > double sum = 0.0 ;
  12. sum ==> 0.0
  13.  
  14. > double average = 0.0 ;
  15. average ==> 0.0
  16.  
  17. > for(int iElem : iArray)
  18. /*
  19. Calculate the sum of the
  20. array referenced by the
  21. variable iArray. */
  22. sum += iElem;
  23.  
  24. > sum
  25. sum ==> 1.0
  26.  
  27. > average = sum / iArray.length ;
  28. average ==> 0.3333333333333333

In the Stream API , IntStream , LongStream , and DoubleStream provide the average and sum methods which can be used , to calculate the average and sum of an array .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4.  
  5. > int iArray[] = { -1, 0, 2 }
  6. iArray ==> [ -1, 0, 2 ]
  7.  
  8. > Arrays.stream(iArray).sum()
  9. $ ==> 1
  10.  
  11. > Arrays.stream(iArray).average()
  12. $4 ==> OptionalDouble[0.3333333333333333]

16- Reducing an array

The Stream API provide the reduce method , which can be used to iterate over all the elements of a stream to perform a combining computation , and return a single value .

The reduce method can be used to calculate the sum , average , min , and max and other functions over a stream . An Array can be converted to a Stream using the Arrays.stream method .

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4. > import java.util.stream.IntStream;
  5. > import java.util.stream.Stream;
  6.  
  7. > int iArray[] = { 1, -2, 3 };
  8. /*
  9. Create an array of type int[] ,
  10. containing the elements ,
  11. 1 , -2 and 3 , and store
  12. a reference of it in the
  13. variable iArray .*/
  14. iArray ==> [ 1, -2, 3 ]
  15.  
  16. > Arrays.stream(iArray).reduce(Integer::sum);
  17. /*
  18. Use Arrays.stream to create
  19. a sequential stream backed by
  20. the array referenced by
  21. iArray .
  22. Using the reduce function ,
  23. compute the sum of the
  24. elements of the stream , by
  25. passing the sum function
  26. of Integer .*/
  27. $ ==> OptionalInt[2]
  28.  
  29.  
  30. > String sArray[] = { "hello ", "world" };
  31. sArray ==> [ "hello ", "world" ]
  32. /*
  33. Create an array of type String[] ,
  34. containing references to the
  35. String "hello" and "world" .
  36. Store a reference of this array
  37. in the variable sArray .*/
  38.  
  39. > Arrays.stream(sArray).reduce((previous , current)-> previous + current );
  40. /*
  41. use Arrays.stream to create
  42. a sequential Stream , backed
  43. by the array referenced by
  44. the variable sArray.
  45. Pass a lambda function to ,
  46. reduce. It receives the previous
  47. computed value , and the current
  48. iterating element , and return
  49. the currently computed value .
  50. reduce returns an Optional .*/
  51. $ ==> Optional[hello world]
  52.  
  53.  
  54. > int iArray[][] = { { 1, 2}, { 3, 4 } }
  55. /*
  56. Create an array of type int[][] ,
  57. and store a reference to it ,
  58. in the variable iArray .*/
  59.  
  60. > Arrays.
  61. stream(iArray).
  62. reduce(
  63. (prev, current)->
  64. IntStream.concat(Arrays.stream(prev) , Arrays.stream(current)).toArray()
  65. ).
  66. get()
  67. /*
  68. This expression creates an
  69. int[] out of an int[][] .
  70. Use Arrays.stream to create a
  71. sequential stream , backed
  72. by the array reference by iArray .
  73. Use reduce method , to pass
  74. a function , which takes a
  75. previous computed value , and
  76. a current iterating value.
  77. The function uses IntStream.concat
  78. method , to concatenate the
  79. streams created from the previous
  80. int [] array and the current int []
  81. array , using the Arrays.stream ,
  82. method.
  83. It then create an array of type
  84. int [] from this stream .
  85. The reduce functions returns an
  86. Optional , and we use the get method
  87. of an Optional to retrieve its
  88. value .*/
  89. $ ==> int[4] { 1, 2, 3, 4 }
  90.  
  91.  
  92. > int iArray[] = {} ;
  93. /*
  94. Create an array of type int[]
  95. , having no elements .
  96. Assign a reference to this array,
  97. in the variable iArray .*/
  98. iArray ==> [ ]
  99.  
  100. > Arrays.stream(iArray).reduce(Integer::sum)
  101. /*
  102. Use Arrays.stream to create
  103. a sequential stream backed
  104. by the array referenced by
  105. iArray.
  106. Pass the Integer::sum function
  107. to reduce , to perform the
  108. summation of the elements of
  109. the stream .
  110. Since no elements are found in
  111. the Stream , reduce returns
  112. an empty optional .
  113. An empty optional , have no value .*/
  114. $ ==> OptionalInt.empty
  115.  
  116. > Arrays.stream(iArray).reduce(0, Integer::sum)
  117. /*
  118. Instead of getting an empty Optional ,
  119. when no elements are present in
  120. the Stream , an initial value ,
  121. can be passed to reduce .
  122. If no elements are found , in the
  123. stream , the initial value is returned .
  124. If elements are found in the stream ,
  125. reduce starts from the provided
  126. initial value .*/
  127. $ ==> 0
  128.  
  129.  
  130. > int iArray[][] = { { 1, 2 }, { 3, 4 } };
  131. iArray ==> [ [ 1, 2 ], [ 3, 4 ] ]
  132. /*
  133. Create an array of type int[][] ,
  134. and store a reference to it ,
  135. in the iArray variable .*/
  136.  
  137. > Arrays.
  138. stream(iArray).
  139. reduce(
  140. IntStream.empty(),
  141. (prev, current)->
  142. IntStream.concat(prev , Arrays.stream(current)),
  143. IntStream::concat
  144. ).
  145. toArray()
  146. /*
  147. Use Arrays.stream to create
  148. a sequential Stream backed by
  149. the array referenced by iArray.
  150. Use reduce method , to convert
  151. this stream which is of type
  152. int [] , into a stream of type
  153. int .
  154. The first argument to reduce ,
  155. is the default or initial value.
  156. It is an empty Stream of type int .
  157. The second argument is a function ,
  158. that will concat the previous
  159. value with the current value ,
  160. using IntStream.concat ,
  161. returning a stream of int .
  162. The previous value is of type
  163. IntStream , whereas the current
  164. value of type int []. As such
  165. Arrays.stream is used to
  166. convert it to a Stream of
  167. type int .
  168. The last argument to reduce , is
  169. a function which will return
  170. a value of the type of the
  171. default value , which in
  172. this case is an IntStream .
  173. The function passed is
  174. IntStream::concat .
  175. An array is created from ,
  176. the created IntStream elements
  177. , using the Stream toArray
  178. method .*/
  179. $ ==> int[4] { 1, 2, 3, 4 }

17- Converting arrays

A list view can be gotten from an array , by using the Arrays.aslist method . The created list , will have the provided array, as its data store , it will be fixed size , and modification to any will affect the other .

  1. jshell>
  2.  
  3. > import java.util.List;
  4. > import java.util.Arrays;
  5. > import java.util.Set;
  6. > import java.util.TreeSet;
  7.  
  8. > Integer iArray[] = new Integer[3] ;
  9. /*
  10. Create an array of type
  11. Integer [] , of length 3 ,
  12. all of its elements contain
  13. a reference to null .
  14. Store a reference to this array ,
  15. in the iArray variable. */
  16. iArray ==> [ null, null, null ]
  17.  
  18. > List<Integer> iList = Arrays.asList(iArray) ;
  19. /*
  20. Create a fixed sized List , backed
  21. by the array reference by the
  22. variable iArray. */
  23. iList ==> [null, null, null]
  24.  
  25. > iList.set(0 , 1 )
  26. /*
  27. Set the first element of the
  28. list to 1 .*/
  29. iList ==> [1, null, null]
  30.  
  31. > iArray
  32. /*
  33. Print the content of the array
  34. referenced by iArray .*/
  35. iArray ==> [ 1, null, null ]
  36.  
  37. > Arrays.fill(iArray , 2 ) ;
  38. /*
  39. Fill the array reference by
  40. iArray with 2 .*/
  41.  
  42. > iList
  43. /*
  44. Print the content of the list
  45. reference by iList . */
  46. iList ==> [2, 2, 2]
  47.  
  48. /*
  49. Once an array is converted to a List ,
  50. Other collections can be gotten .*/
  51.  
  52. > Set<Integer> sInteger = new TreeSet<Integer>(iList);
  53. /*
  54. Create a TreeSet from the
  55. list referenced by iList .
  56. A Set contains no duplicate .*/
  57. sInteger ==> [2]

The Arrays.stream method , can be used to create a sequential stream backed by the provided array . A stream can be collected into various Collections , such as List , Set ...

  1. jshell>
  2.  
  3. > import java.util.Arrays;
  4. > import java.util.stream.Collectors;
  5.  
  6. > Integer iArray [] = { 1, 2, 2, 1, 0 }
  7. /*
  8. Create an array of type int [] ,
  9. containing the elements ,
  10. 1 , 2 , 2 , 1 , 0 .
  11. Store a reference to this
  12. array in the variable iArray .*/
  13. iArray ==> [ 1, 2, 2, 1, 0 ]
  14.  
  15. > Arrays.stream(iArray).collect(Collectors.toList());
  16. /*
  17. Use Arrays.stream method to
  18. create a sequential stream ,
  19. backed by the array reference
  20. by iArray .
  21. Use the Stream collect method ,
  22. by passing to it a Collector .
  23. The collector accumulate the
  24. elements of the stream into a
  25. List .*/
  26. $ ==> [1, 2, 2, 1, 0]
  27.  
  28. > Arrays.stream(iArray).collect(Collectors.toSet());
  29. /*
  30. Use Arrays.stream to create
  31. a sequential stream backed
  32. by the array referenced by
  33. the iArray variable.
  34. Use the Stream collect method ,
  35. to pass a Collector , which
  36. collect the elements of the
  37. Stream into a Set .*/
  38. $ ==> [0, 1, 2]
  39.  
  40. > Arrays.stream(iArray).skip(3).collect(Collectors.toCollection(PriorityQueue::new));
  41. /*
  42. Use Arrays.stream method , to
  43. create a sequential stream ,
  44. backed by the array referenced
  45. by the iArray variable.
  46. Use skip , to create a Stream ,
  47. which skipped three elements
  48. of the previous stream .
  49. Use Collect function , passing to
  50. it a Collector , which will
  51. collect the element of the
  52. Stream , into a PriorityQueue .*/
  53. $ ==> [0, 1, 2, 2, 1]

18- Reversing an Array

To reverse an array , one can use this method :

  1. int anArray[] = {1, 2 ,4 };
  2.  
  3. for(int i = 0 ; i < anArray.length / 2 ; i++ )
  4. {
  5. int tmp = anArray[i];
  6. anArray[i] = anArray[anArray.length - i - 1];
  7. anArray[anArray.length - i - 1 ] = tmp ;
  8. }
  9.  
  10. /*
  11. anArray ==> [ 4, 2, 1 ]
  12. */

19- Cartesian product of Two arrays

The Cartesian product of two arrays , can be calculated as follows :

  1. int anArrayOne[] = { 1, 2, 4 } ;
  2.  
  3. int anArrayTwo[] = { 4, 5, 6 } ;
  4.  
  5. int aCartesianProduct[][][] = new int[anArrayOne.length][anArrayTwo.length][2];
  6.  
  7. for (int i = 0 ; i < anArrayOne.length ; i++)
  8. for(int j = 0 ; j < anArrayTwo.length ; j++)
  9. aCartesianProduct[i][j] = new int[]{anArrayOne[i],anArrayTwo[j]};
  10.  
  11. /*
  12. Output :
  13. [[[1, 4], [1, 5], [1, 6]], [[2, 4], [2, 5], [2, 6]], [[4, 4], [4, 5], [4, 6]]]*/