Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 394
Glenn Avatar asked Oct 19 '22 04:10

Glenn


2 Answers

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.

like image 57
Kevin Wheeler Avatar answered Oct 21 '22 22:10

Kevin Wheeler


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;
}
like image 33
MABVT Avatar answered Oct 21 '22 21:10

MABVT