Skip to content
Advertisement

String Arraylist get the item starting with this string

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

MyStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");

Now I have a string String sweet="c"; Now what OI want is to filter that Arraylist based on my string(sweet) so the items of the MyStrings will be only Cat and Can

EDIT I am really sorry for the trouble I got you but my main problem is that sweet is a editable Ive tried using this code

      public void onTextChanged(CharSequence s, int start, int before,int count) {  
        //adapter2.getFilter().filter(s);
        //int length = filterEditText.getText().length();
        filterME  = filterEditText.getText();
        List<String> MySortStrings =new ArrayList<String>();
        for(int i=0;i<MyStrings.size();i++)
        {
            String newString = MyStrings.get(i);
            if (newString.startsWith(filterME)){

            }
        }
        //adapter2 = new LazyAdapterGetFriends(MyFriends.this,x);
         //list.setAdapter(adapter2);
    }

using this declaration

    LazyAdapterGetFriends adapter2;
ArrayList<String> MyStrings;
//List<String> MyStrings;
EditText filterEditText;

Sorry for my wrong question.. Foolish me

Advertisement

Answer

List<String> MyStrings =new ArrayList<String>();
List<String> MySortStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");
String sweet="c";
for(int i=0;i<MyStrings.size();i++)
{
    if(MyStrings.get(i).startsWith(sweet.toUpperCase()))
    {
        MySortStrings.add(MyStrings.get(i));
    }
}

System.out.println(MySortStrings.size());

The list MySortStrings contains the Cat & Can

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement