Need the Index No of an Array List, by giving the certain text of the element String

72 Views Asked by At

I want to get the particular index of the array list, by using only contained text. Say suppose,

I have arraylist as

Test = {"LabTechnician","SeniorLabTechnician_4","Pathologist","SeniorLabTechnician_6"}

If want the index nos of both the SeniorLabTechnician, i have to use the exact string in the indexOf and lastindexOf method. Like Test.indexOf("SeniorLabTechnician_4") and Test.lastindexOf("SeniorLabTechnician_6")

this is will get me the exact answer.. But instead of that,by using only prefix say like senior or some thing like, i want the exact same answer before..

Like Test.indexOf("Senior") and Test.lastindexOf("Senior")...

Please suggest

3

There are 3 best solutions below

4
On
private int getsearchPos(String searchvalue) {
  for(String hj : Test)
     {
         if(hj.toLowerCase().startsWith(searchvalue.toLowerCase()))
                      return Test.indexOf(hj);
     }
    return -1;
}

this should help.

4
On

Loop over the list and compare the elements with contains:

int indexOfContains(List<String> lst, String what) {
  for(int i=0;i<lst.size();i++){
    //this will make the check case insensitive, see JAVY's comment below:
    //if(lst[i].toLowerCase().contains(what.toLowerCase())) {
    if(lst[i].contains(what)){
      return i;
    }
  }
  return -1;  
}

If you want something like lastIndexOf then just reverse the order in which the list is iterated.

1
On

As I understand, you want to modify default behaviour of indexOf and lastIndexOf methods of ArrayList.

  1. My solution is create a new class CustomArrayList extends ArrayList.
  2. Override indexOf method
  3. Override lastIndexOf method

    public class CustomArrayList extends ArrayList {
    
      public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size(); i++)
                if (get(i) == null)
                    return i;
        } else {
            for (int i = 0; i < size(); i++)
                if(o instanceof String) {
                    if(get(i).toString().startsWith(o.toString())) {
                        return i;
                    }
                } else {
                    if (o.equals(get(i)))
                        return i;
                }
        }
        return -1;
    }
    
    public static void main(String[] args) {
        List list = new CustomArrayList();
        list.add("LabTechnician");
        list.add("SeniorLabTechnician_4");
        list.add("Pathologist");
        list.add("SeniorLabTechnician_6");
        System.out.println(list.indexOf("Senior"));
    }
    

    }

I left overriding of lastindexof method for you.