jyomin
jyomin

Reputation: 1967

How to check whether a String is present in the Custom Array or not?

I have an array of private SearchAutoSuggestResult[] mArrSearchAutoSuggest; where the Cusom class is

 public class SearchAutoSuggestResult
{
    private String did;

    private String Res;

    public String getDid ()
    {
        return did;
    }

    public void setDid (String did)
    {
        this.did = did;
    }

    public String getRes ()
    {
        return Res;
    }

    public void setRes (String Res)
    {
        this.Res = Res;
    }
    @Override
    public String toString()
    {
        return "ClassPojo [did = "+did+", Res = "+Res+"]";
    }

}

How i can check String Res lets say "Hello" is present in the array and at what position.

Upvotes: 0

Views: 161

Answers (3)

Arthur Eirich
Arthur Eirich

Reputation: 3638

You will need to loop through your array:

for(int i = 0; i < mArrSearchAutoSuggest.length; i++) {
  SearchAutoSuggestResult result = mArrSearchAutoSuggest[i];
  String res = result.getRes();
  if(res != null && res.equals("Hello") { //means the result exists ans its value is "Hello"
    System.out.print(res);
    System.out.println(i); //prints the position of result  in the array
  }
}

Upvotes: 1

Kartheek
Kartheek

Reputation: 7214

You can use the Arrays class to search whether an element is present in the array.

Arrays.binarySearch(array[],key);

it returns the index of given key in the given array if present otherwise it returns -1. Make sure your bean has implemented hashcode() and equals() method.

Upvotes: 0

Pankaj Deshpande
Pankaj Deshpande

Reputation: 502

first, convert your array to arraylist, then check if expected string exists in that arraylist as below:

    public boolean isKeyExists(String array[], String key) {
    List<String> myList = new ArrayList<String>(Arrays.asList(array));
    return myList.contains(key);
}

Upvotes: 1

Related Questions