How to find filter int[] array to find certain value is present or not inside array.
Checking the int array for given element is very with the use of for loop. Because using for loop developer can easily check all the elements of int[] array one by one. So here is the complete step by step tutorial for Check if an int array contains a certain value in Java Android.
How to Check if an int array contains a certain value in Java Android.
Code for MainActivity.java file.
package com.intarraycontainscertainvalue_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { TextView textview1,textview2; int[] intarray = new int[]{1,2,3,4,5,6,7,8,9,0}; int i = 0; boolean Check = false; int ElementForFound = 7; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textview1 = (TextView)findViewById(R.id.textView1); textview2 = (TextView)findViewById(R.id.textView2); //Printing the whole array on screen. while( i <intarray.length) { textview1.setText(textview1.getText() + " " + intarray[i] + " , "); i++; } //Checking array contain 7 . for (int i=0;i<intarray.length;i++){ if(intarray[i] == ElementForFound){ Check = true; break; } } if(Check == true) { textview2.setText("Element Found"); } else { textview2.setText("Not Found"); } } }
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.intarraycontainscertainvalue_android_examples.com.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@+id/textView1" android:layout_marginTop="27dp" android:text="Show Here" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
Screenshot: