I want to know how to iterate through the following Arraylist.
public class FruitHandler {
private ArrayList<Fruits> fruit;
private ArrayList<Integer> fruitUID= new ArrayList<>();
public static FruitHandler getInstance() {
return instance;
}
public void addFruit(Fruit fruit) {
this.fruitUID.add(fruit.getfruitUID());
this.fruit.add(fruit);
}
}
What I want to do is to iterate through the fruitUID and return the instance of that fruit class that is stored in ArrayList<Fruits> fruit
which matches my given UID.
Example, I have an fruitUID = 10
, I want to have the reference of the instance of the fruit class that is stored in ArrayList<Fruits> fruit
which have its fruitUID = 10
.
If you want to retrieve a Fruit
instance given a fruitUID then you probably want a Map<Integer, Fruit>
.
You could also just have a list of Fruit
instances and use a stream and a filter to find just the single instance with a specified fruitUID.
If you absolutely must use two lists, then you need find the index of the specified fruitUID and extract the Fruit
from the other list at the same index.
Edit: If you want to use a map:
private Map<Integer, Fruits> fruits = new HashMap<>();
public void addFruit(Fruit fruit) {
fruits.put(fruit.getfruitUID(), fruit);
}
public Fruit findFruit(Integer fruitUID) {
return fruits.get(fruitUID);
}