String Arraylist get the item starting with this string

后端 未结 5 1720
长情又很酷
长情又很酷 2021-02-09 15:35

I have a array list in which I bind the data This is a example

MyStrings =new ArrayList();
MyStrings.add(\"Dog\");
MyStrings.add(\"Cat\");
MyString         


        
5条回答
  •  旧时难觅i
    2021-02-09 16:13

    The naive algorithm will be that you just filter everything out like this:

    ArrayList filtered = new ArrayList();
    for(String s : MyStrings){
    if(s.substring(0,1).toLowerCase().equals("c")){
    filtered.add(s);
    }
    }
    

    but then you have access time in O(n).

    if you need a more faster way you probably need to use a Key,Value Structure with Key set to the String you need to filter. Or even a http://en.wikipedia.org/wiki/Trie, where you can easily filter on every character in the string. But then you will need extra time in building up this thing.

    Okay, this should be it when using your TextWatcher Stuff (untested...)

      private List MySortStrings = new ArrayList(); // assume that your data is in here!
      private List MySortedStrings = new ArrayList(); // this will be the list where your sorted strings are in. maybe you could also remove all strings which does not match, but that really depends on your situation!
    
      public void onTextChanged(CharSequence s, int start, int before,int count) {  
        for(String str : MySortStrings){
            if(str.startsWith(s.toString()){
                MySortedStrings.add(str);
            }
        }
    }
    

提交回复
热议问题