Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Arraylist get the item starting with this string

Tags:

java

android

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

like image 567
Androyd Avatar asked Sep 10 '12 09:09

Androyd


2 Answers

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

like image 103
Ram kiran Pachigolla Avatar answered Oct 19 '22 22:10

Ram kiran Pachigolla


Use str.startsWith(String, int index)

Index will tell you from which index in the str it should start comparing

like image 22
abhi Avatar answered Oct 19 '22 22:10

abhi