用java中的for循环填充HashMap
我试图用for循环填充LinkedHashMap,以便在我的jsf页面中使用它,但是当新的“put”方法被触发时,hashmap的“put”方法会覆盖hashmap中保存的值 方法是这样的,用java中的for循环填充HashMap,java,hashmap,Java,Hashmap,我试图用for循环填充LinkedHashMap,以便在我的jsf页面中使用它,但是当新的“put”方法被触发时,hashmap的“put”方法会覆盖hashmap中保存的值 方法是这样的, public static List<String> valuesOfEnum() throws JsonProcessingException { Map<String, Object> newArray = new LinkedHashMap<String,
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;
}
public static List valuesOfEnum()抛出JsonProcessingException{
Map newArray=newlinkedhashmap();
List jsonObj=new ArrayList();
字符串json=null;
对于(limantilimantii:values()){
newArray.put(“id”,limantii.getId());
newArray.put(“value”,limantii.getValue());
json=newObjectMapper().writeValueAsString(newArray);
jsonObj.add(json);
}
返回jsonObj;
}
下面是jsf代码
<f:selectItems value="#{denizlimaniViewController.limanTipleri}" var="limanTipleri" itemValue="#{limanTipleri.id}" itemLabel="#{limanTipleri.value}"/>
使用此方法,我将hashmap转换为list,因为我无法正确填充hashmap,但这不是我想要的,因为我无法在
中使用此列表
我需要使用itemValue和itemLabel来表示hashmap中的“id”和“value”属性
有办法解决这个问题吗
谢谢密钥get被覆盖,因为您总是将密钥设置为
id
和value
。修改您的代码,如下所示:
for(LimanTipi limanTipi : values()){
newArray.put(limanTipi.getId(), limanTipi.getValue());
json = new ObjectMapper().writeValueAsString(newArray);
jsonObj.add(json);
}
<f:selectItems value="#{denizlimaniViewController.limanTipleri.entrySet()}"
var="limanTipleri"
itemValue="#{limanTipleri.key}" itemLabel="#{limanTipleri.value}" />
编辑:
HopelimanTipleri
就是地图newArray
本身。然后您需要修改代码,如下所示:
for(LimanTipi limanTipi : values()){
newArray.put(limanTipi.getId(), limanTipi.getValue());
json = new ObjectMapper().writeValueAsString(newArray);
jsonObj.add(json);
}
<f:selectItems value="#{denizlimaniViewController.limanTipleri.entrySet()}"
var="limanTipleri"
itemValue="#{limanTipleri.key}" itemLabel="#{limanTipleri.value}" />
每个键必须不同,请使用newArray.put(limantii.getId(),limantii.getValue());所以,如果每个键都不同,put方法不会覆盖,对吗@Martinspameri这是什么?这是map
newArray
?@N.Doye主要问题是每次id
,value
键被覆盖(这些键被硬编码,在for循环执行之后,mapid
和value
中只有两个键,并且映射包含最后被覆盖的值)。您必须为非常value(limantii.getValue())
value创建不同的键。您必须创建类似于以下内容的映射:javax.el.PropertyNotFoundException:Property[value]未在类型[java.lang.String]上找到此异常引发的映射。如果我在我的问题中添加jsf代码可能会更好