check if array contains a value java code example
Example 1: Check if an array contains an element java
import java.util.Arrays;
String[] array = {"Boto", "Nesto", "Lepta"};
String toSearch = "Nesto";
if (Arrays.toString(array).contains(toSearch)) {
}
String strArray = Array.toString(array);
if (strArray.contains(toSearch)) {
}
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int number = 5;
String checker = Arrays.toString(numbers);
if (checker.contains(Integer.toString(number)) {
}
Example 2: java check if element exists in array
package com.mkyong.core;
import java.util.Arrays;
import java.util.List;
public class StringArrayExample1 {
public static void main(String[] args) {
String[] alphabet = new String[]{"A", "B", "C"};
List<String> list = Arrays.asList(alphabet);
if(list.contains("A")){
System.out.println("Hello A");
}
}
}
Copy
Example 3: java check if element exists in array
boolean result = Arrays.stream(alphabet).anyMatch("A"::equals);
if (result) {
System.out.println("Hello A");
}
Copy
Example 4: check if array contains a number in java
public static boolean contains(final int[] arr, final int key) {
return Arrays.stream(arr).anyMatch(i -> i == key);
}