Java Basics:Java Arrays-1

 

Java Program to Concatenate Two Arrays

Example 1: Concatenate Two Arrays using arraycopy

import java.util.Arrays;

public class Concat {

    public static void main(String[] args) {
        int[] array1 = {1, 2, 3};
        int[] array2 = {4, 5, 6};

        int aLen = array1.length;
        int bLen = array2.length;
        int[] result = new int[aLen + bLen];

        System.arraycopy(array1, 0, result, 0, aLen);
        System.arraycopy(array2, 0, result, aLen, bLen);

        System.out.println(Arrays.toString(result));
    }
}

Output

[1, 2, 3, 4, 5, 6]

In the above program, we've two integer arrays array1 and array2.

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen.

Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

The arraycopy(array1, 0, result, 0, aLen) function, in simple terms, tells the program to copy array1 starting from index 0 to result from index 0 to aLen.

Likewise, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2 starting from index 0 to result from index aLen to bLen.


Example 2: Concatenate Two Arrays without using arraycopy

import java.util.Arrays;

public class Concat {

    public static void main(String[] args) {
        int[] array1 = {1, 2, 3};
        int[] array2 = {4, 5, 6};

        int length = array1.length + array2.length;

        int[] result = new int[length];
        int pos = 0;
        for (int element : array1) {
            result[pos] = element;
            pos++;
        }

        for (int element : array2) {
            result[pos] = element;
            pos++;
        }

        System.out.println(Arrays.toString(result));
    }
}

Output

[1, 2, 3, 4, 5, 6]

In the above program, instead of using arraycopy, we manually copy each element of both arrays array1 and array2 to result.

We store the total length required for result, i.e. array1.length + array2. length. Then, we create a new array result of the length.

Now, we use the for-each loop to iterate through each element of array1 and store it in the result. After assigning it, we increase the position pos by 1, pos++.

Likewise, we do the same for array2 and store each element in result starting from the position after array1.

Java Program to Check if An Array Contains a Given Value

Example 1: Check if Int Array contains a given value

class Main {
  public static void main(String[] args) {

    int[] num = {1, 2, 3, 4, 5};
    int toFind = 3;
    boolean found = false;

    for (int n : num) {
      if (n == toFind) {
        found = true;
        break;
      }
    }
    
    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

Output

3 is found.

In the above program, we have an array of integers stored in variable num. Likewise, the number to be found is stored in toFind.

Now, we use a for-each loop to iterate through all elements of num and check individually if toFind is equal to n or not.

If yes, we set found to true and break from the loop. If not, we move to the next iteration.


Example 2: Check if an array contains the given value using Stream

import java.util.stream.IntStream;

class Main {
  public static void main(String[] args) {
    
    int[] num = {1, 2, 3, 4, 5};
    int toFind = 7;

    boolean found = IntStream.of(num).anyMatch(n -> n == toFind);

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
      
  }
}

Output

7 is not found.

In the above program, instead of using a for-each loop, we convert the array to an IntStream and use its anyMatch() method.

anyMatch() method takes a predicate, an expression, or a function that returns a boolean value. In our case, the predicate compares each element n in the stream to toFind and returns true or false.

If any of the element n returns truefound is set to true as well.


Example 3: Check if an array contains a given value for non-primitive types

import java.util.Arrays;

class Main {
  public static void main(String[] args){

    String[] strings = {"One","Two","Three","Four","Five"};
    String toFind= "Four";

    boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind));

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

Output

Four is found.

In the above program, we've used a non-primitive data type String and used Arrays's stream() method to first convert it to a stream and anyMatch() to check if the array contains the given value toFind.

__________________________________________________________

Java Program to Convert the ArrayList to an array and vice versa

Example 1: Convert the Arraylist into Array

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // Add elements in the arraylist
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("ArrayList: " + languages);

    // Create a new array of String type
    String[] arr = new String[languages.size()];

    // Convert ArrayList into the string array
    languages.toArray(arr);
    System.out.print("Array: ");
    for(String item:arr) {
      System.out.print(item+", ");
    }
  }
}

Output

ArrayList: [Java, Python, JavaScript]
Array: Java, Python, JavaScript,

In the above example, we have created an arraylist named languages. Notice the line,

languages.toArray(arr);

Here, the toArray() method converts the arraylist languages into an array. And stores it in the string array arr.

Note: If we don't pass any argument to the toArray() method, the method returns an array of the Object type.


Example 2: Convert Array to ArrayList

import java.util.Arrays;
import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // create an array
    String[] array = {"Java", "Python", "C"};
    System.out.println("Array: " + Arrays.toString(array));

    // convert array to arraylist
    ArrayList<String> languages= new ArrayList<>(Arrays.asList(array));

    System.out.println("ArrayList: " + languages);

  }
}

Output

Array: [Java, Python, C]
ArrayList: [Java, Python, C]

In the above example, we have created an array of String type. Notice the expression,

Arrays.asList(array)

Here, the asList() method of the Arrays class converts the specified array into the arraylist.

Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Selenium-Java Contents

Java OOPS:Constructors in Java – A complete study!!