I'm working on a restful api that manage a backpack inventory just for learning. But I'm struggling with the creation feature wich is responsible to persist a new inventory. So every time that I make a POST request to my api, I receive an list of itens to my new inventory, than I have to process the quantity of each item and with that I get the value for an atribue of the item object called "points".
The json object that my api receive is something like this:
{
"inventory": [
{
"name": "Meat",
"quantity": 4
},
{
"name": "Water",
"quantity": 1
},
{
"name": "Wood",
"quantity": 7
},
{
"name": "Iron",
"quantity": 3
}
]
}
The system has just four type of items, for each type I get a specific amount of points.
Example:
Meat - 6 points
Water - 7 points
Wood - 3 points
Iron - 2 points
Now I have to process the quantity of each item to got my points. The problem is my java method don't verify my item name properly. Because that, the method give null into my points property when I persist the new inventory.
My Item class looks like this one:
public class Item {
private String name;
private Integer quantity;
private Integer points;
//get and set omitted;
}
My Backpack class look like this:
public class Backpack{
private List<Item> inventory;
//get and set ommited;
}
The method responsible to receive and process my points looks like this
@PostMapping()
public void createInventory(@RequestBody Backpack backpack) {
backpack.getInventory().stream().forEach(i -> i.setPoints(calcPoints(i)));
backpackDao.persistInventory(backpack);
}
public Integer calcPoints(Item item) {
if (item.getName().toLowerCase() == "meat")
return item.getQuantity * 6;
if (item.getName().toLowerCase() == "water")
return item.getQuantity * 7;
if (item.getName().toLowerCase() == "wood")
return item.getQuantity * 3;
if (item.getName().toLowerCase() == "iron")
return item.getQuantity * 2;
return null;
}
I set the item name to lower case just to make the conditional check a little easy. In case someone could try to persist with up case string. If I try print each item after my stream operation I can got my item name and item quantity but with points with null. I've tryed print a simple log to know if my method calcPoints is calling, and it is. But for some reason the conditionals are not working. I'd like some advice or suggestions about how I can solve this. I think that maybe is something simple but I'm really don't see it yet.