Java Program to Check if an Array Contains a Given Value

Java Program to Check if an Array Contains a Given Value

Are you curious to know ” How to use Java program to check if an array contains a given value

Arrays often store collections of data. Imagine a scenario in a college’s student management system: you have an array containing student records, and you need to find a specific student by their name in order to enroll them in a particular course section. In such cases, verifying whether the student you’re looking for exists in the array becomes important. Without this validation step, you risk enrolling the wrong student or encountering errors due to missing data.

Checking and Validation ensures data integrity and avoid errors. Whether you’re building a student management system, a shopping cart application, or any software that involves data manipulation, the ability to check for specific values in arrays is a foundational skill for any programmer. And, to understand this topic more clearly you need to first understand the process of printing an array in Java

In this beginner-friendly post, we will discuss no. of ways to check if an array holds a particular value.

  1.   Using loop/linear Search
  2.   Using Arrays.asList and contains
  3.   Arrays.stream and `anyMatch`
  4.   Arrays.Stream and `anyMatch` (primitives)

By the end of this post, you’ll have a clear understanding of each of these methods and be well-equipped to employ them in your own Java programming projects.

 Let’s understand each one of them bit by bit:

Method 1: Using Linear Search

Java code using linear search:

				
					public class ArrayContainsExample {
	public static boolean containsValue(int[] digits, int value) {
    	for (int element: digits) {
        	if (element == value) {
            	return true;
        	}
    	}
    	return false;
	}
 
	public static void main(String[] args) {
    	int[] digits = { 1, 2, 3, 4, 5 };
    	int targetValue = 3;
 
    	boolean contains = containsValue(digits, targetValue);
 
    	if (contains) {
        	System.out.println("Array contains the value " + targetValue);
    	} else {
        	System.out.println("Array does not contain the value " + targetValue);
    	}
	}
}

				
			

This code segment defines a linear search algorithm. The ` containsValue ` function takes in an array and a target element and performs a straightforward linear search to find whether the array element is equal to the target element or not. If an element is found it returns `true` otherwise returns `false`.

Output:

Array contains the value 3

In this code, since the `targetValue` is 3, and 3 is present in the digits array, the program will print “Array contains the value 3” to the console.

Method 2 : Using `Arrays.asList` and `contains` function

Java code using `Arrays.asList` and `contains` function

				
					import java.util.Arrays;
import java.util.List;
 
public class ArrayContainsExample {
	public static void containsValue(String[] array, String value) {
    	List < String > list = Arrays.asList(array);
    	boolean res = list.contains(value);
 
    	if (res) {
        	System.out.println("Array contains the value " + value);
    	} else {
        	System.out.println("Array does not contain the value " + value);
    	}
 
	}
 
	public static void main(String[] args) {
    	String[] fruits = {
        	"apple",
        	"banana",
        	"jackfruit",
        	"avacado"
    	};
    	String targetFruit1 = "cherry";
    	String targetFruit2 = "banana";
 
    	containsValue(fruits, targetFruit1);
    	containsValue(fruits, targetFruit2);
	}
}

				
			

Did you face difficulties in understanding the above code? No need to worry, you can always ask for Java project help for CodingZap experts. . The `containsValue` function in this code takes String array and Target String and converts the string array into a list using `Arrays.asList()`. It then uses list class built-in method `contains` to check if the specified value is present in the list. If the value is found, it prints the message.

Output :

Array does not contain the value cherry

Array contains the value banana

In the main method, two different target values, “cherry” and “banana,” are checked within the fruits array. Since `cherry` is not present inside the array while banana is present, it outputs the correct msg.

 Method 3:  Using `Arrays.stream` and `anyMatch`  method.

Java code using `Arrays.stream` and `anyMatch` :

				
					import java.util.Arrays;
public class ArrayContainsExample {
    public static boolean containsValue(String[] array, String value) {
    	return Arrays.stream(array).anyMatch(element -> element.equals(value));
	}
 
	public static void main(String[] args) {
 
    	String[] colors = {
        	"red",
        	"green",
        	"blue",
        	"yellow"
    	};
    	String targetColor = "blue";
    	boolean contains = containsValue(colors, targetColor);
 
    	if (contains) {
        	System.out.println("Array contains the value " + targetColor);
    	} else {
        	System.out.println("Array does not contain the value " + targetColor);
    	}
	}
}

				
			

The function uses the `Arrays.stream()` method  to create a stream , iterates through the array stream  and checks if a specified element is present or not using lambda expression. If a match is found, it returns true, indicating that the array contains the value; otherwise, it returns false.

However, this section of code uses .equals() method to find matches since String is an object (non-primitive) data type.

Output :

Array contains the value blue

Target color `blue` is matched in the String `colors` array . Therefore the output indicates blue is present.

Method 4: Using Java 9+ Arrays::stream and anyMatch (for primitive arrays)

Java Code using Java 9+ Arrays::stream and anyMatch (for primitive arrays):

				
					import java.util.Arrays; 
public class ArrayContainsValue {
	public static void main(String[] args) {
    	// Sample array
    	int[] numbers = {
        	1,
        	2,
        	3,
        	4,
        	5
    	};
 
    	// Value to check for
    	int targetValue = 3;
 
    	// Use Arrays.stream() and anyMatch() to check if the value exists
    	boolean found = Arrays.stream(numbers).anyMatch(value -> value == targetValue);
 
    	// Check and display the result
    	if (found) {
        	System.out.println("The array contains the value " + targetValue + ".");
    	} else {
	        System.out.println("The array does not contain the value " + targetValue + ".");
    	}
	}
}

				
			

The code starts with a sample array of numbers and a target value to search for. It then uses `Arrays.stream()` to create a stream of integers from the array and `anyMatch()` to check if any element in the stream matches the target value using a lambda expression. If a match is found, it prints the msg.

This section of code uses == operator to find matches since an integer array is a primitive data type.

Output:

The array contains the value 3

Conclusion:

In this post, we discussed four methods to use Java programs to check if an array contains a given value. The first method demonstrates the linear search technique to find the target element using a loop. Array.asList method simplifies the above process by list conversion and then using the `contains` method. `Arrays.stream` creates a stream and uses `anyMatch` to efficiently search for target value. Lamda expression is used to check for appropriate match. .equals and == operator is used for String objects and primitive arrays. Also, if are you curious to know about the difference between Array and ArrayList then you can check out our article. 

Leave a Comment

Your email address will not be published. Required fields are marked *