Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

Wednesday, December 22, 2021

Java Program to Calculate Standard Deviation

1. Overview

In this tutorial, you'll learn how to calculate the standard deviation in java using for loop and its formula.


2. Example to calculate standard deviation

Let us write a simple java program to find the standard deviation for an individual series of numbers.

First create a method with name calculateStandardDeviation(). Create an array with integer values and. pass this array to the calculateStandardDeviation() method. This method has the core logic to get the standard deviation and. returns to main method.

package com.javaprogramto.programs.arrays.calculation;

public class StandardDeviation {

	public static void main(String[] args) {

		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

		double standardDeviation = calculateStandardDeviation(array);

		System.out.format("Standard deviation : %.6f", standardDeviation);

	}

	private static double calculateStandardDeviation(int[] array) {

		// finding the sum of array values
		double sum = 0.0;

		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		// getting the mean of array.
		double mean = sum / array.length;

		// calculating the standard deviation
		double standardDeviation = 0.0;
		for (int i = 0; i < array.length; i++) {
			standardDeviation += Math.pow(array[i] - mean, 2);

		}

		return Math.sqrt(standardDeviation/array.length);
	}

}
 

Output:

Standard deviation : 2.581989
 

3.  Conclusion

In this article, you've seen how to find the standard deviation in java.

As usual, the shown example is over GitHub.


Tuesday, December 21, 2021

Java Array Sort Descending Order or Reverse Order

1. Overview

In this tutorial, We'll learn how to sort the arrays in revere order in java.
Sorting arrays is done with the help of Comparator interface which works very well for the custom objects.

Array of ints or any primitive/wrapper types  can be sorted in descending order using Arrays.sort() method.

Arrays.sort(T[], Collections.reverseOrder());
Arrays.sort(ints, Collections.reverseOrder());
Arrays.sort(stringArray, Collections.reverseOrder());
Arrays.sort(empArray, Collections.reverseOrder());

Let us write the few examples on arrays reverse order sorting.

Java Array Sort Descending Order

Monday, December 20, 2021

How To Compare Two Arrays In Java and New Java 8 API

1. Overview

In this article, you'll learn how to compare two arrays in java and how to work with comparing the contents of arrays using the deep level technique.

Comparing arrays means the first array type should be the same and contents also should be the same in both arrays.

All the examples are prepared with Arrays.equals() and Arrays.deepEquals() methods.

How To Compare Two Arrays In Java and New Java 8 API

Friday, December 17, 2021

Java Array Insert - Add Values At The Specific Index

1. Overview

In this tutorial, We'll learn how to insert an element at the specific index for the given array in java.

if you are new to java, Please read the below articles on arrays.



This can be done in two ways. Let us write the example code to insert the value at any given position.

All examples shown in this article are present in GitHub and it is provided at the end of the article.

Java Array Insert - Add Values At The Specific Index


Thursday, December 9, 2021

Java Arrays Sort Comparator

1. Overview

In this tutorial, we'll learn how to sort arrays in java with the comparator.

Comparator is used to write the custom sorting with the Collections or over Arrays.

If you are new arrays, read articles on Arrays.



At the end of the article, we have given the GitHub link where you can see all code at once and you can run the programs along with me.

It is easy to sort the arrays when the array is single-dimensional. Use Arrays.sort() method.

But if you have the user defined objects or two dimensional arrays then it is not possible to sort by using just the Arrays sort() method.

In this case, we need to use the Comparator interface to provide the custom logic for it.

First, we will start with the custom objects and then next show the two or more dimensional arrays.

You will see the different ways to create the comparator in jdk8, java 7 and before versions. All will produce the same output.

Java Arrays Sort Comparator

Monday, November 29, 2021

How to create and initialize boolean array in java?

1. Overview

In this tutorial, We'll how to use boolean array and how to initialize boolean array in java.

Boolean array is used to store the only boolean values. boolean value can be either true or false.

The default value of boolean type is false and the default value of the primitive boolean array is false for all indexes.

Boolean array references are initialized with null values.

In some cases, the default value is false is not useful. To make the default value true, we need to use the Arrays.fill() method.

How to create and initialize boolean array in java?

Saturday, November 27, 2021

Java Nested Arrays - Multidimensional Arrays Examples

1. Overview

In this article, We'll learn how to create and access nested or multidimensional arrays.

Example programs on single, 2D and 3D dimensional arrays in java.


Java Nested Arrays - Multidimensional Arrays Examples

Tuesday, November 23, 2021

Java - How to return empty array?

1. Overview

In this tutorial, we'll learn how to return an empty array in java in different ways.

An empty array means the array is not having any values and the length of the array is zero. Sometimes we need to return an empty array rather than returning null values.

Creating an empty array can be done in 3 ways.


All examples work for any type of array ex. int, double, custom type such as Emp, Student etc.

Java - How to return empty array?


Java Copy Array - 4 Ways to copy from one to another Array

1. Overview

In this tutorial, You'll learn how to copy the array from one to another without loosing any values.

If you are new to java programming, learn how to create an array in java in various ways? 

Copying an array can be done in multiple ways. Let us discuss all possible ways.

Read the article till end to see best option for your case.

2. Copy Array Using Another Reference


Let us first create an array with 5 values and assign to a variable originalArray.

In the next step, create a new reference variable named "copiedArray" and assign the originalArray to copiedArray.

Further, printing the two arrays on the console using "Arrays.toString()" method.
import java.util.Arrays;

public class CopyArrayRefAssignment {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// assigning to the original array to new ref.
		int[] copiedArray = originalArray;

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}

Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [100, 2, 3, 4, 500]

From the above output, you could see that originalArray and copiedArray have the same values.

But, we changed the values of original array using its index. After that printed the original and copied arrays. 

You might have noticed that copiedArray values are changed as per the modified original array.

Hence, it is not advisable to use the array assignment if original array is going to be modified in future because two references points to same object in the heap memory area.

3. Copy Array Using Iteration


Second approach is to iterate the array using for loop and assign each value to new array.
public class CopyArrayRefIterateExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// assigning to the original array to new ref.
		int[] copiedArray = new int[originalArray.length];

		// iterating array and assigning to the new array

		for (int i = 0; i < originalArray.length; i++) {
			copiedArray[i] = originalArray[i];
		}

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [1, 2, 3, 4, 5]

In this approach, we need to copy the each value to new array. You can observe the output is that any changes to the original array does not affect the copied array.

4. Copy Array Using Clone Approach


Next third approach, you'll see the example program using clone() method. You can understand the differences between deep copy vs shallow copy cloning in java.
public class CopyArrayCloneExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// cloning array using clone() method
		int[] copiedArray = originalArray.clone();
		

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
Output:
Original Array : [1, 2, 3, 4, 5]
Copied Array : [1, 2, 3, 4, 5]

Printing values after original array modifications
Modified Original Array : [100, 2, 3, 4, 500]
Copied Array : [1, 2, 3, 4, 5]

This approach works fine as similar to the above approach.

5. Copy Array Using System.arraycopy() Method


In the last approach, you'll use the System.arraycopy() method which does copy the values from original array for a given index range.
public class CopyArraySystemArraycopyExample {

	public static void main(String[] args) {
		// creating an array

		int[] originalArray = { 1, 2, 3, 4, 5 };

		// Creating a new array as same as original. 
		int[] copiedArray = new int[originalArray.length];

		// cloning array using clone() method
		System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);

		// printing the arrays
		System.out.println("Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

		// changing the values in the original array

		originalArray[0] = 100;
		originalArray[4] = 500;

		// printing both arrays after modification

		System.out.println("\nPrinting values after original array modifications");
		System.out.println("Modified Original Array : " + Arrays.toString(originalArray));

		System.out.println("Copied Array : " + Arrays.toString(copiedArray));

	}

}
This approach also work well and could see it as used in many collections api internally.

Hence, this approach is better choice if you want to copy the large data set which is stored in array.

6. Conclusion


In this article, you've seen the various ways to copy array to another in java.

GitHub sample code


Monday, November 22, 2021

Java Arrays - How to return array in java from method?

1, Overview


In this tutorial, We'll learn how to return an array from a method in java.

If you are new to java programming, please refer to the article on How to initialize an array in java?

Thump rules:

  • A method can return an array that is referencing another array.
  • The return type of method must be declared as the correct array type.
Java Return arrays - How to return array in java from method?

Wednesday, November 17, 2021

Java Add To Array - How to add element to an array in Java?

1. Overview

In this tutorial, We'll be learning how to add new values to an array in java. 

In java, once the array is created then it can not be resized. That means increasing or reducing the size in java is not possible.

You need to look for alternative ways to add to array in java.

Adding int or string to an array can be implemented in ways as below.

A) By recreating the new array
B) By intermediate storage such as ArrayList or HashSet if the array values are unique.

This works for any type of array such as adding to int array or string array.
Java Add To Array - How to add element to an array in Java?

Tuesday, January 26, 2021

Java Arrays.setAll() Examples To Modify Existing Array

1. Overview

In this article, You'll learn how to use JDK 1.8 Arrays.setAll() method to modify the existing values of the array with a unique generator function. Arrays class is part of java.util package.

This method sets all elements of the specified array, using the provided generator function to compute each element.

In the previous article, We've seen how to set the whole array with the same value using Arrays.fill() method?

Java Arrays.setAll() Examples

Friday, October 23, 2020

Java Program to Find Largest Element of an Array(+Java 8 Approach)

1. Overview

In this article, you'll learn how to find the largest value from an array. You should know the basic understanding of java Arrays, for-each loopand java 8 lambdas.

Finding the biggest value can be done in different ways.

Let us explore 3 different ways using for each loop, sort() method,  java 8 streams.

Note: Array is not sorted. if is sorted in ascending already then take the value from the array the last index-1 which gives the biggest value. If sorted descending, take zero index value.

Java Program to Find Largest Element of an Array(+Java 8 Approach)

Wednesday, October 14, 2020

Java Program to Calculate Average Using Arrays

1. Overview

In this article, you'll learn how to calculate the average of numbers using arrays

You should know the basic concepts of a java programming language such as Arrays and forEach loops.

We'll see the two programs on this. The first one is to iterate the arrays using for each loop and find the average.

In the second approach, you will read array values from the user.

Let us jump into the example programs.

Java Program to Calculate Average Using Arrays


2. Example 1 to calculate the average using arrays

First, create an array with values and run. the for loop to find the sum of all the elements of the array.

Finally, divide the sum with the length of the array to get the average of numbers.

package com.javaprogramto.programs.arrays.average;

public class ArrayAverage {

	public static void main(String[] args) {

		// create an array
		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

		// getting array length
		int length = array.length;

		// default sium value.
		int sum = 0;

		// sum of all values in array using for loop
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		double average = sum / length;
		
		System.out.println("Average of array : "+average);

	}

}

Output:

Average of array : 6.0

3. Example 2 to find the average from user inputted numbers

Next, let us read the input array numbers from the user using the Scanner class.

Scanner Example to add two numbers

import java.util.Scanner;

public class ArrayAverageUserInput {

	public static void main(String[] args) {

		// reading the array size.
		Scanner s = new Scanner(System.in);

		System.out.println("Enter array size: ");
		int size = s.nextInt();
		// create an array
		int[] array = new int[size];

		// reading values from user keyboard
		System.out.println("Enter array values :  ");
		for (int i = 0; i < size; i++) {
			int value = s.nextInt();
			array[i] = value;

		}

		// getting array length
		int length = array.length;

		// default sium value.
		int sum = 0;

		// sum of all values in array using for loop
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		double average = sum / length;

		System.out.println("Average of array : " + average);

	}

}

Output:

Enter array size: 
5
Enter array values :  
12
23
34
45
56
Average of array : 34.0

4. Conclusion

In this article, you've seen how to calculate the average number in an array.

All examples shown are in GitHub.

Average

Monday, October 12, 2020

Java Program to Check if An Array Contains a Given Value or Not (+Java 8)

1. Overview

In this article, you'll learn how to check an array contains the given value in it or not.

It is not mandatory to have complete knowledge of the arrays but you should know the following.

how to create and initialize an array in java.

How to declare the variables in java?

Java Program to Check if An Array Contains a Given Value or Not (+Java 8)


2. Example 1 To check the given number in the array using the native approach

This is a simple approach to search the given value in an array and this is called a linear search algorithm.

package com.javaprogramto.programs.arrays.search;

public class FIndValue {

	public static void main(String[] args) {

		int[] array = { 1, 4, 6, 2, 5 };

		int findValueOf = 6;

		boolean isFound = false;
		for (int i = 0; i < array.length; i++) {

			if (array[i] == findValueOf) {
				isFound = true;
				break;
			}

		}

		if (isFound) {
			System.out.println("Number " + findValueOf + " is found in the  array");
		} else {
			System.out.println("Number " + findValueOf + " is not found in the  array");
		}
	}

}

Output:

Number 6 is found in the  array

In the above example for loop is used to iterate over the array values and compare each value with the findValueOf variable value.

3. Example 2 To find the number using Java 8 Streams for primitive values

Next, let us use the Java 8 Stream API to check the given value in an array or not.

Now, we are checking with primitives values so you should use the IntStream.

First, convert an array to int stream using IntStream.of() method and call anyMatch() method to check value.

import java.util.stream.IntStream;

public class IntStreamFindValue {

	public static void main(String[] args) {

		int[] array = { 10, 30, 20, 90, 40, 60 };

		int findValueOf = 90;

		boolean isFound = false;

		isFound = IntStream.of(array).anyMatch(condition -> condition == findValueOf);

		if (isFound) {
			System.out.println("Number " + findValueOf + " is found in the array in java 8");
		} else {
			System.out.println("Number " + findValueOf + " is not found in the  array in java 8");
		}
	}

}

Output:

Number 90 is found in the array in java 8

If a number is found in the array then anyMatch() returns true else false.

4. Example 3 To find the number using Java 8 Streams for non-primitive values

In the above section, you've seen for primitive arrays but how can you find in the string array.

Interestingly, the same anyMatch() method works for any type of array.

import java.util.Arrays;

public class IntStreamFindStringValue {

	public static void main(String[] args) {

		String[] stringArray = new String[] { "hello", "how", "life", "is", "going" };

		String findString = "java";

		boolean isFound = false;

		isFound = Arrays.stream(stringArray).anyMatch(value  -> value.equals(findString));

		if (isFound) {
			System.out.println("String " + findString + " is found in the array in java 8");
		} else {
			System.out.println("String " + findString + " is not found in the  array in java 8");
		}
	}

}

Output:

String java is not found in the  array in java 8

5. Conclusion

In this article, you've seen the different ways to check if an array contains a given value or not and also examples using java 8 api.

As usual, all examples are over GitHub.

Arrays

Stream.anyMatch()

How To Initialize An Array In Java In Different Ways

1. Overview

In this article, You'll learn how to initialize the array in java. Array creation can be done in different ways.

Typically, Arrays are a collection of the value of that of the same type. You can not store the different types of values inside the array.

This is the underlying structure that is widely used in the Collection API and problem solving interview questions.

All the values stored inside the array are called as elements and each element is stored at a unique index. Array index starts from ZERO.

How To Initialize An Array In Java In Different Ways


But, Collection api is preferred over arrays if you are doing insertions in middle or resizing the array.

2. How To Declare An Array?

Declaring array is pretty straight forward. Look at the below syntax.

DataType[] arrayName ;

All the below three segments are mandatory in the array declaration.

Data Type: Data type defines the type of objects or values are stored inside array such as int, boolean, char, float, etc.
[] : Square brackets indicates as an array.
arrayName: Variable name is to access the array values from memory.
package com.javaprogramto.arrays.initialize;

public class ArrayDeclaration {

    public static void main(String[] args) {
        
        // int array declaration
        int[] intArray;

        // boolean array declaration
        boolean[] statusArray;

        // float array declaration
        float[] salaryArray;
    }
}

3. Initializing An Array


In the above section, you understood how to declare an array. Now, let us understand some basic rules about the array initialization.

Declaring an array means that does not array is initialized. To store the values inside an array, You must have to initialize the array first.

Below is the syntax to initialize the array.
DataType[] arrayname = new DataType[size];
new keyword and size must be specified to create an array.

Array initialization can be done in different ways. Let us explore all the possible ways to create and store the values in an array.

4. Initializing An Array Without Assigning Values


Java allows initializing the values at all indexes at the time of its creation.

In the below example program, We are creating an array with its default values
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationDefaultValues {

    public static void main(String[] args) {

        // int array initialization
        int[] intArray = new int[9];

        System.out.println("Printing array values : ");
        for(int i = 0; i < intArray.length ; i++){
            System.out.println(intArray[i]);
        }

    }
}
Output:
Printing array values : 
0
0
0
0
0
0
0
0
0

Created and initialized an array with size 9 and did not assign any values in the program. When we run the for loop on intArray then it printed 0 for all indexes.

Note: Array length can be accessed through a special variable name called "length". This length is available on all array variables.

5. Initializing An Array After Declaration


If you observe in the above program, the Array is declared and initialized in a single line. But there is a way to declare the array first and next initialize an array with values.
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationAfterDeclaration {

    public static void main(String[] args) {

        // Example 1
        // int array declaration
        int[] intArray;

        // Array initialization
        intArray = new int[]{10, 20, 30, 40, 50};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration
        boolean[] booleanArray ;

        // boolean array initialization
        booleanArray = new boolean[]{true, false, true};

        System.out.println("Printing boolean array : ");
        for(int index = 0;index < booleanArray.length; index++){
            System.out.println(booleanArray[index]);
        }
    }
}

Output:
Printing array values : 
10
20
30
40
50
Printing boolean array : 
true
false
true

In this example, Created two arrays, intArray stores int values, booleanArray stores boolean values.
These two arrays are first declared and in the next line initialized with its values.

Note: When an array is initialized with values in the next line than that array creation must use a "new" keyword. Otherwise, You will get the compile-time error saying "Array initialization is not allowed here"

6. Initializing An Array And Assigning Values Without Using new Keyword


Still, there is a way to initialize the array without using the new keyword. But, this is allowed only at the time of array declaration. If you try to do the same in the next line will give the compile-time error.

Let us see the examples.

int[] intArray = {2, 4, 6, 8, 20};

boolean[] booleanArray = {true, false, true};

double[] salaryArray = {15000, 35000, 50000};

Here, a new keyword is not used and size is calculated based on the values added to the array at declaration.

Full example program
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationWithoutNewKeyword {

    public static void main(String[] args) {

        // Example 1
        // int array declaration and intialization without new keyword
        int[] intArray = {2, 4, 6, 8, 20};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration and intialization without new keyword
        boolean[] booleanArray = {true, false, true};

        System.out.println("Printing boolean array : ");
        for (int index = 0; index < booleanArray.length; index++) {
            System.out.println(booleanArray[index]);
        }

        // Example 3

        // Double array declaration and intialization without new keyword
        double[] salaryArray = {15000, 35000, 50000};

        System.out.println("Printing salary double array : ");
        for (int index = 0; index < salaryArray.length; index++) {
            System.out.println(salaryArray[index]);
        }
    }
}

7. Initializing the Wrapper Arrays and Employee Array


As of now, you've seen how to create and initialize an array for primitive types. But, the same can be applied to the Wrapper classes, String, and also for user-defined classes.

Observe the below examples and all are valid.
package com.javaprogramto.arrays.initialize;

import com.javaprogramto.models.Employee;

public class ArrayInitializationForNonPrimitives {

    public static void main(String[] args) {

        // Array initialization without the "new" keyword
        String[] stringArray = {"hello", "welcome"};

        // String Array initialization with "new" keyword
        String[] newStringArray = new String[]{"hello", "welcome"};

        Employee e1 = new Employee(100, "Jhon", 30);
        Employee e2 = new Employee(101, "Amal", 25);
        Employee e3 = new Employee(102, "Paul", 35);

        // Employee Array initialization without "new" keyword
        Employee[] empArrayWithoutNewKeyword = {e1, e2, e3};

// Employee Array initialization without "new" keyword Employee[] empArrayWithNewKeyword = new Employee[]{e1, e2, e3}; } }

8. Create and Initialize An Array With Size Zero(0)


Many developers who started learning java will get the common question is it possible to create an array with size 0?

The answer is yes it is possible and array has zero values in it and here are the few examples.
 		// Array initialization without the "new" keyword with size 0
        String[] stringArray = {};

        // String Array initialization with "new" keyword with size 0
        String[] newStringArray = new String[0];

        // Employee Array initialization without "new" keyword with size 0
        Employee[] empArrayWithoutNewKeyword = {};

        // Employee Array initialization with "new" keyword with size 0
        Employee[] empArrayWithNewKeyword = new Employee[0];
        

9. Conclusion


In this article, You've seen how to create and initialize an array in java in different ways.

Array related interesting articles others reading


All examples are shown are over GitHub.


Friday, October 9, 2020

Java Program To Remove Duplicates From Array (Without Using Set)

1. Overview

In this article, you'll learn how to remove the duplicate values from array in different ways using java programming.

Let us learn how to work with the sorted and unsorted array for this scenario.

In the previous article, we've explained the different ways to remove duplicates from List in Java 8?

Java Program To Remove Duplicates From Array (Without Using Set)


Wednesday, October 7, 2020

Java Program To Get Intersection Of Two Arrays

1. Overview

In this tutorial, you'll learn how to get the intersection of two arrays in java.  An Intersection Set is a common values among all collections. 

In our case, you need to get the values that are common in both arrays.

For example, Look at the below two arrays.

Array 1: { 1, 2, 3, 4, 5}

Array 2: {2,  4,  6,  8}

In these two arrays, 2 and 4 are the common values so these 2,4 set is an intersection of Array 1 and Array 2.

Java Program To Get Intersection Of Two Arrays


We are going to write the java program using HashSet and retainAll() method.

retainAll() Example to get unique and duplicate values from the list

We've seen in the previous article, how to get a union of two arrays of integers or string values.

Monday, October 5, 2020

Java Program To Get Union Of Two Arrays

1. Overview

In this article, you'll learn how to get the union of two arrays in java.  A union set is all the values of two sets or from all collection.

We can do the union function in java using HashSet with arrays. Use the addAll() method to add all the values of each array into HashSet.

This is a simple solution. As well as this solution will work with both numbers and string values.

Java Program To Get Union Of Two Arrays


2. Union of two Integer arrays with numbers

Let us write the java program to print the union of two integer arrays.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class UnionTwoArraysNumbers {

	public static void main(String[] args) {

		// Integer array 1
		Integer[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
		System.out.println("Array 1 : " + Arrays.toString(array1));

		// Integer array 2
		Integer[] array2 = { 2, 4, 6, 8, 10, 12, 14 };
		System.out.println("Array 2 : " + Arrays.toString(array2));

		// creating a new Set
		Set<Integer> unionOfArrays = new HashSet<>();

		// adding the first array to set
		unionOfArrays.addAll(Arrays.asList(array1));

		// adding the second array to set
		unionOfArrays.addAll(Arrays.asList(array2));

		// converting set to array.
		Integer[] unionArray = {};
		unionArray = unionOfArrays.toArray(unionArray);

		// printing the union of two arrays.
		System.out.println("Union of two arrays: " + Arrays.toString(unionArray));

	}

}

Output:

Array 1 : [1, 2, 3, 4, 5, 6, 7, 8]
Array 2 : [2, 4, 6, 8, 10, 12, 14]
Union of two arrays: [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14]

3. Union of two String arrays

Let us write the java program to print the union of two String arrays.


public class UnionTwoArraysStrings {

	public static void main(String[] args) {

		// Integer array 1
		String[] array1 = { "A", "B", "C", "D" };
		System.out.println("String Array 1 : " + Arrays.toString(array1));

		// Integer array 2
		String[] array2 = { "C", "D", "E", "F" };
		System.out.println("String  Array 2 : " + Arrays.toString(array2));

		// creating a new Set
		Set<String> unionOfArrays = new HashSet<>();

		// adding the first array to set
		unionOfArrays.addAll(Arrays.asList(array1));

		// adding the second array to set
		unionOfArrays.addAll(Arrays.asList(array2));

		// converting set to array.
		String[] unionArray = {};
		unionArray = unionOfArrays.toArray(unionArray);

		// printing the union of two arrays.
		System.out.println("Union of two String arrays: " + Arrays.toString(unionArray));

	}

}

Output:

String Array 1 : [A, B, C, D]
String  Array 2 : [C, D, E, F]
Union of two String arrays: [A, B, C, D, E, F]

4. Conclusion

In this article, we've seen how to find the union of two arrays in java using HashSet.

As usual, all examples. are over Github.

How to compare two strings?

How to add integers to ArrayList?

HashSet

String API Methods

Integer API

Thursday, August 13, 2020

How To Convert ArrayList To String Array In Java 8 - toArray() Example

1. Overview

In this article, You're going to learn how to convert ArrayList to String[] Array in Java. ArrayList is used to store the List of String using the toArray() and Stream API toArray() method.

How To Convert ArrayList To String Array In Java 8 - toArray() Example