How to check arraylist contains this particular word in android?

I have an ArrayList<String> that I added 3-4 site names. For example, http://www.google.com , https://www.stackoverflow.com , etc. Now in my application, if I just type β€œgoogle”, then I want to compare this word β€œgoogle” with ArrayList<String> .

I'm stuck here. Can someone tell me how can I compare a string with an array object?

Thanks in advance.

+6
source share
4 answers

To do this, you need to override the implementation of contains() . I give you a simple example.

Custom class ArrayList

 public class MyArrayList extends ArrayList<String> { private static final long serialVersionUID = 2178228925760279677L; @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public int indexOf(Object o) { int size = this.size(); if (o == null) { for (int i = 0; i < size ; i++) { if (this.get(i) == null) { return i; } } } else { for (int i = 0; i < size ; i++) { if (this.get(i).contains(String.valueOf(o))) { return i; } } } return -1; } } 

How to use

 MyArrayList arrayList = new MyArrayList(); arrayList.add("http://www.google.com"); arrayList.add("https://www.stackoverflow.com"); arrayList.add("http://pankajchunchun.wordpress.com"); if (arrayList.contains("google")) { System.out.println("ArrayList Contains google word"); } if (arrayList.contains("igoogle")) { System.out.println("ArrayList Contains igoogle word"); } else { System.out.println("ArrayList does not Contains igoogle word"); } 

Below is the sample code above

 ArrayList Contains google word ArrayList does not Contains igoogle word 

For more information, see ArrayList Source Code .

+5
source

ArrayList.contains() check the String value is equal. From the documentation:

public boolean contains (Object o) Returns true if this list contains the specified element. More formally returns true if and only if the list contains at least one element e such that (o == null? E == null: o.equals (e)).

Example:

 boolean contains = yourArrayListInstance.contains(yourString); 

Change If you want to check the substring, you need to loop around the contents of the ArrayList and call String.contains

+3
source

You can iterate through ArrayList<String> as

 public String getWebsiteName(String toMatchString) { ArrayList<String> yourArrayList = new ArrayList<String>(); for (String webSiteName : yourArrayList) { if (webSiteName.contains(toMatchString)) return webSiteName; } return null; } 

and get String matching

+1
source

Use a helper function like this

 public static boolean containsSubString(ArrayList<String> stringArray, String substring){ for (String string : stringArray){ if (string.contains(substring)) return true; } return false; } 
0
source

All Articles