Glenn
Glenn

Reputation: 655

Search for object property in list of objects android

The class:

public class Category {

    private String name;
    private String baseUnit;

    public Category() {   
    }

    public Category(String name, String baseUnit) {
        this.name = name;
        this.baseUnit = baseUnit;
    }
}

In my code I have a list of category objects:
List<Category> categories = new ArrayList<Category>();

I have a string e.g. category_1_name but how do I get the category-object in categories where category.name=category_1_name?

Upvotes: 5

Views: 2312

Answers (2)

Kevin Wheeler
Kevin Wheeler

Reputation: 1452

public static Category findCategory(Iterable<Category> categories, String name)
{
    for(Category cat : categories) //assume categories isn't null.
    {
        if(name.equals(cat.name)) //assumes name isn't null.
        {
            return cat;
        }
    }

    return null;
}

Otherwise, I'm sure there are convenience libraries to do these kinds of things. I know underscore/lodash is the library people would use to do stuff like this in javascript. I'm not sure about Java.

Upvotes: 2

MABVT
MABVT

Reputation: 1360

Unfortunately there s no built in functionality like LINQ for C# but a simple method should suffice:

static Category findCategoryByName(ArrayList<Category> categories, String name) 
{
    if(categories == null 
        || name == null
        || name.length() == 0) 
        return null;

    Category result = null;

    for(Category c : categories) {
        if(!c.getName().equals(name))
            continue;

        result = c;
        break;
    }

    return result;
}

Upvotes: 1

Related Questions