Reputation: 20130
I have an abstract class like this:
public abstract class Ingredient {
protected int id;
}
and a list
List <Ingredient> ingredientList = new ArrayList <Ingredient>()
I want to be able to get an Ingredient from the ingredientList
using id.
I did something like this:
public abstract class Ingredient implements Comparable<Ingredient>{
protected int id;
@Override
public int compareTo(Ingredient o) {
// TODO Auto-generated method stub
if (this.id > o.id){
return 1;
}
return 0;
}
}
but still not working
Upvotes: 1
Views: 301
Reputation: 26740
If you use Eclipse Collections you can use the detect method.
final int idToFind = ...;
ListIterable<Ingredient> ingredientList = FastList.newListWith(...);
Ingredient ingredient = ingredientList.detect(new Predicate<Ingredient>()
{
public boolean accept(Ingredient eachIngredient)
{
return eachIngredient.getId() == idToFind;
}
});
If you cant change the type of ingredientList, you can still use the static utility form of detect.
Ingredient ingredient = ListIterate.detect(ingredientList, new Predicate<Ingredient>()
{
public boolean accept(Ingredient eachIngredient)
{
return eachIngredient.getId() == idToFind;
}
});
When Java 8 is released lambdas, you will be able to shorten the code to:
Ingredient ingredient = ingredientList.detect(eachIngredient -> eachIngredient.getId() == idToFind);
Note: I am a committer for Eclipse collections.
Upvotes: 1
Reputation: 8926
public Ingredient getIngredientById(int id) {
for (Ingredient ingredient : ingredientList) {
if (ingredient.id == id) {
return ingredient;
}
}
}
Upvotes: 0
Reputation: 5595
for (Ingredient ingredient : IngredientList) {
if (ingredient.getId() == id) {
System.out.println("found");
}
}
System.out.println("not found");
Upvotes: 2
Reputation: 28727
When you use List.contains()
to find the Ingredient with id, then override equals()
and hashCode() { return id};
In equals(): in equal compare this.id with other.id .
Upvotes: 0
Reputation: 431
Just a guess, but could it be that this is what you mean:
Best way to use contains in an ArrayList in Java?
contains() method of list uses equals() and hashCode()
Upvotes: 0
Reputation: 159754
If you need to perform regular lookups, a Map
is probably a better collection to use here:
Map<Integer, Ingredient> ingredientMap = new HashMap<>();
Upvotes: 2
Reputation: 1171
you can do (within you class)
interface Callback { public void handle(Indredient found); }
public void search(List<Ingredient> ingredientList, int id, Callback callback) {
for(Ingredient i : ingredientList) if(i.id == id) callback.handle(i)
}
and then
ingredients.search ( 10, new Callback() {
public void handle(Ingredient found) {
System.out.println(found);
}
});
or something similar...
ps.: i answered before you changed you question ;)
Upvotes: 0