Skip to content

Instantly share code, notes, and snippets.

@gauravkukade
Last active May 17, 2021 15:31
Show Gist options
  • Save gauravkukade/a93dd0faec3bebd75fa9833d5089d482 to your computer and use it in GitHub Desktop.
Save gauravkukade/a93dd0faec3bebd75fa9833d5089d482 to your computer and use it in GitHub Desktop.
A java program to check if an array contains a value suing the Apache common lang library's `ArrayUtils.contains()` method. Check the blogpost at https://coderolls.com/java-check-if-array-contains-value-or-element/
import org.apache.commons.lang3.ArrayUtils;
/**
* A java program to check if an array contains a value suing the
* Apache common lang library's ArrayUtils.contains() method
*
* @author Gaurav Kukade at coderolls.com
*
*/
public class ArrayUtilsExample {
public static void main(String[] args) {
// check in primitive ( int[]) array
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int intToCheck = 8;
boolean containsInt = ArrayUtils.contains(numbers, intToCheck);
if(containsInt){
System.out.println("The numbers array contians the value '"+intToCheck+"'.");
}else {
System.out.println("The numbers array does not contian the value '"+intToCheck+"'.");
}
// check in String array
String[] names = {"gaurav", "shubham", "krishna", "mayur"};
String stringToCheck = "gaurav";
boolean containsString = ArrayUtils.contains(names, stringToCheck);
if(containsString) {
System.out.println("String value '"+stringToCheck+"' is present in names array.");
}else {
System.out.println("String value '"+stringToCheck+"' is not present in names array.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment