【发布时间】:2018-06-01 23:14:21
【问题描述】:
我正在开发一个用于管理背包库存的 restful api,仅用于学习。 但是我正在努力使用负责保持新库存的创建功能。 因此,每次我向我的 api 发出 POST 请求时,我都会收到一个指向我的新库存的项目列表,然后我必须处理每个项目的数量,并由此获得项目对象属性的值,称为“点”。
我的 api 接收到的 json 对象是这样的:
{
"inventory": [
{
"name": "Meat",
"quantity": 4
},
{
"name": "Water",
"quantity": 1
},
{
"name": "Wood",
"quantity": 7
},
{
"name": "Iron",
"quantity": 3
}
]
}
系统只有四种类型的物品,每种类型我都会获得特定数量的积分。
例子:
Meat - 6 points
Water - 7 points
Wood - 3 points
Iron - 2 points
现在我必须处理每个项目的数量以获得我的积分。 问题是我的 java 方法没有正确验证我的项目名称。因为那样,当我持久化新库存时,该方法将 null 赋给我的 points 属性。
我的 Item 类看起来像这样:
public class Item {
private String name;
private Integer quantity;
private Integer points;
//get and set omitted;
}
我的背包课是这样的:
public class Backpack{
private List<Item> inventory;
//get and set ommited;
}
负责接收和处理我的积分的方法是这样的
@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;
}
我将项目名称设置为小写只是为了使条件检查更容易一些。万一有人可以尝试坚持使用大写字符串。 如果我在流操作后尝试打印每个项目,我可以获得我的项目名称和项目数量,但点为空。 我尝试打印一个简单的日志,以了解我的方法 calcPoints 是否正在调用,并且确实如此。但由于某种原因,条件句不起作用。 我想要一些关于如何解决这个问题的建议或建议。我认为这可能很简单,但我真的还没有看到。
【问题讨论】:
-
您无需串流列表即可致电
forEach()。 -
感谢您的建议@shmosel。我改变了。