N. Doye
N. Doye

Reputation: 45

Populating HashMap with for loop in java

I'm trying to populate LinkedHashMap with for loop in order to use it in my jsf page but "put" method of hashmap overwrites the values that is held in hashmap when the new "put" method is fired.

The method is like that;

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;
    }

Here's the jsf code;

<f:selectItems value="#{denizlimaniViewController.limanTipleri}" var="limanTipleri" itemValue="#{limanTipleri.id}" itemLabel="#{limanTipleri.value}"/>

With this method, I convert the hashmap into list as I couldn't populate the hashmap properly but this is not what I want because I can't use this list in <f:selectItems>.

I need to use itemValue and itemLabel representing "id" and "value" properties in hashmap.

Is there a way to handle this?

Thanks

Upvotes: 1

Views: 1328

Answers (1)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

Key get's overwritten because you always have keys as id and value. Modify your code like below:

for(LimanTipi limanTipi : values()){
            newArray.put(limanTipi.getId(), limanTipi.getValue());
            json = new ObjectMapper().writeValueAsString(newArray);
            jsonObj.add(json);
        }

EDIT:

Hope limanTipleri is the map newArray itself. Then you need to modify your code like below:

<f:selectItems value="#{denizlimaniViewController.limanTipleri.entrySet()}" 
               var="limanTipleri" 
               itemValue="#{limanTipleri.key}" itemLabel="#{limanTipleri.value}" />

Upvotes: 1

Related Questions