我在努力从充满对象的数组列表中获取属性。我想找到属于某个餐点的所有菜肴,并按盘类型进行筛选,并在视图的表格中显示它们。
所以我已经编写了getDishNameByType方法,但是它将返回null。任何帮助将不胜感激!
Meal.Java
public class Meal {
@Id
@GeneratedValue
private Long id;
@ManyToMany
private Set<Dish> dishesList = new HashSet<>();
public String getDishNameByType(String dishType) {
for (Dish dish : dishesList) {
if (dishType == dish.getDishType()) {
return dish.getDishName();
}
}
return null;
}
}
Dish.Java
public class Dish {
@Id
@GeneratedValue
private Long id;
private String dishName;
private String dishType;
@ManyToMany(mappedBy = "dishesList")
private Set<Meal> mealsList = new HashSet<>();
View.html
<tr th:if="${mealPage.empty}">
<td colspan="7" th:text="#{meals.list.table.empty}">No meals found</td>
</tr>
<tr th:each="meal : ${mealPage}">
<td th:text="${meal.id}">1</td>
<td th:each="dish : ${meal.dishesList}"
th:text="${meal.getDishNameByType("Maincourse")}"></td>
</tr>
答案 0 :(得分:1)
如果您有两个对象obj1
和obj2
,则当且仅当两个对象相同时,obj1 == obj2
才是true
。
String foo = "abc";
String bar = "abc";
boolean same = (foo == bar); //false
boolean similar = (foo.equals(bar)); //true
因此,您需要致电equals
:
public String getDishNameByType(String dishType) {
for (Dish dish : dishesList) {
if ((dishType.equals(dish.getDishType()))) {
return dish.getDishName();
}
}
return null;
}