Hello I'm having an issue figuring out a way to search an multi-dimensional arraylist for a string. I'm developing an adventure text-based game and in the game, you will collect items. I've defined an item as the following
public Item(String aName,String aDescription,String Type, double weight, double value, int amount) {
this.Name = aName;
this.Description = aDescription;
this.weight = weight;
this.value = value;
this.Type = Type;
this.amount = amount;
}
When attempting to add an item, I need to be able to check the arraylist to see if the list contains the item already so that I can add to the int amount for that item. Here is what I've tried.
if(itemInvent.contains("Bear Pelt")){
int indexBear = itemInvent.indexOf("Bear Pelt");
int amount = itemInvent.get(indexBear).getAmount();
amount = 1;
itemInvent.get(indexBear).setAmount(amount);
}else {
itemInvent.add(new Item("Bear Pelt","Skin of a Bear","Crafting Item",1,80,1));
}
This doesn't seem to work as expected.
CodePudding user response:
i think as @tgdavies is true where you can create map since finding element in map is faster than List as map hash key then it directly while list search all elements to find your element
Map<String, Item> map = new HashMap<>();
So, you can check as the follwoing:
if(map.containsKey("Bear Pelt")){
Item myItem = map.get("Bear Pelt");
myItem.set()//put all your setters
}else{
Item myItem = map.get("Bear Pelt");
myItem.set()//put all your setters
}
CodePudding user response:
Since instances of Item
are stored within an ArrayList you can just iterate through the Item
s to see if you already have the inventory item. If you do then increment the count by 1 and if not then add it to the Inventory List:
// An ArrayList which holds instances of Item
ArrayList<Item> itemInvent = new ArrayList<>();
boolean itemExists = false;
for (Item itm : itemInvent) {
if (itm.getName().equalsIgnoreCase("Bear Pelt")) {
int amount = itm.getAmount(); // get current amount...
amount ; // increment bear pelts amount by 1
itm.setAmount(amount); // set the new amount for this Item instance
itemExists = true; // flag to indicate we already have the item
break; // Get otta here...we don't need this anymore.
}
}
//if the flag is still false then we don't have bear pelts...add it.
if (!itemExists) {
itemInvent.add(new Item("Bear Pelt", "Skin of a Bear", "Crafting Item", 1, 80, 1));
}
CodePudding user response:
You can use stream(), findAny()
Optional<Item> optional = itemInvent.stream().filter(item -> item.equalsIgnoreCase("Bear Pelt").findAny();
if (!optional.isPresent()) {
// add to list
}