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
?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With