search an element in an array java code example
Example 1: 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 2: search an element in an array java
import java.util.Scanner;
public class Search_Element
{
public static void main(String[] args)
{
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element you want to find:");
x = s.nextInt();
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("Element found at position:"+(i + 1));
}
else
{
System.out.println("Element not found");
}
}
}
Example 3: java find element in array
array[array.indexOf(element)]
Example 4: java check if element exists in array
boolean result = Arrays.stream(alphabet).anyMatch("A"::equals);
if (result) {
System.out.println("Hello A");
}
Copy