我正在尝试使用 for 循环填充 LinkedHashMap ,以便在我的 jsf 页面中使用它,但使用 hashmap 的“put”方法当新的“put”方法被触发时,覆盖 hashmap 中保存的值。
方法就是这样;
public static List<String> valuesOfEnum() throws JsonProcessingException {
Map<String, Object> newArray = new LinkedHashMap<String, Object>();
List<String> jsonObj = new ArrayList<String>();
String json = null;
for(LimanTipi limanTipi : values()){
newArray.put("id", limanTipi.getId());
newArray.put("value", limanTipi.getValue());
json = new ObjectMapper().writeValueAsString(newArray);
jsonObj.add(json);
}
return jsonObj;
}
这是 jsf 代码;
<f:selectItems value="#{denizlimaniViewController.limanTipleri}" var="limanTipleri" itemValue="#{limanTipleri.id}" itemLabel="#{limanTipleri.value}"/>
使用此方法,我将 HashMap 转换为列表,因为我无法正确填充 HashMap ,但这不是我想要的,因为我无法在 <f:selectItems>
中使用此列表.
我需要使用 itemValue 和 itemLabel 来表示 HashMap 中的“id”和“value”属性。
有办法解决这个问题吗?
谢谢
最佳答案
Key get 被覆盖,因为您始终将键作为 id
和 value
。修改您的代码如下:
for(LimanTipi limanTipi : values()){
newArray.put(limanTipi.getId(), limanTipi.getValue());
json = new ObjectMapper().writeValueAsString(newArray);
jsonObj.add(json);
}
编辑:
Hope limanTipleri
是 map newArray
本身。然后你需要修改你的代码如下:
<f:selectItems value="#{denizlimaniViewController.limanTipleri.entrySet()}"
var="limanTipleri"
itemValue="#{limanTipleri.key}" itemLabel="#{limanTipleri.value}" />
关于java - 在java中使用for循环填充HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51418136/