Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Arraylist find index

I have an ArrayList of object in my Fragment.

ArrayList<MenuListItem> menuItems = new ArrayList<MenuListItem>();
menuItems.add(new MenuListItem("Newsfeed", 20));
menuItems.add(new MenuListItem("FriendsRequest", 1));
menuItems.add(new MenuListItem("Messages", 2));

private class MenuListItem {
    public String label;
    public int count;

    public MenuListItem(String label, int count) {
        this.label = label;
        this.count = count;
    }
}

How can I find the index of object that has the label value "Messages" in my ArrayList from my Activity.

like image 667
LoveMeSomeFood Avatar asked Jul 31 '26 11:07

LoveMeSomeFood


2 Answers

have you try to iterate through elements of menuItems?

something of this sort:

for(MenuListItem menuListItem : menuItems){
    if (menuListItem.label.equals(<what you are looking for>){
        <do something>
        break; // in case when 1st occurence is sufficient
    }
}

side note (not related make your members private and add accessors for them)

Edit: just noticed that you are looking for an index, what i have included is to get an MenuListItem what you can do is iterate and return index if you want.

like image 167
Алексей Avatar answered Aug 02 '26 00:08

Алексей


try

        String search="Messages";
        for(int i=0;i<menuItems.size();i++){
            if(menuItems.get(i).label.equalsIgnoreCase(search)){
                System.out.println("Index " + i);
                break;
            }
        }
like image 26
upog Avatar answered Aug 02 '26 01:08

upog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!