JavaDeveloper
JavaDeveloper

Reputation: 102

Iterating a LinkedHashMap which contains another one

I have a LinkedHashMap which contains another LinkedHashMap as below:

LinkedHashMap<String,LinkedHashMap<String,String>> containerMap = new LinkedHashMap<String,LinkedHashMap<String,String>>();

I want to extract the values from the container Map individually? I mean for each key of the container map I have a LinkedHashMap I want to use that to display in my dropdown list on my JSP

Any ideas?

Upvotes: 0

Views: 401

Answers (2)

Syam S
Syam S

Reputation: 8499

I assume you need multiple dropdowns based on container map. If so from you sevlet set the map to request object as request.setAttribute("containerMap", containerMap) and the use nested forEach loop of jstl in jsp

 <c:forEach items="${containerMap}" var="containerEntry" >
    <select name="${containerEntry.key}" id="${containerEntry.key}">
    <c:forEach items="${containerEntry.value}" var="innerEntry">
        <option value="${innerEntry.key}">
            <c:out value="${innerEntry.value}" />
        </option>
    </c:forEach>
</c:forEach>

Upvotes: 1

Anton Sarov
Anton Sarov

Reputation: 3748

LinkedHashMap<String,LinkedHashMap<String,String>> containerMap = new LinkedHashMap<String,LinkedHashMap<String,String>>();

I omitted the types (assuming you are using at least Java 7)

LinkedHashMap<String, String> lhMap1 = new LinkedHashMap<>();
lhMap1.put("a", "b");
LinkedHashMap<String, String> lhMap2 = new LinkedHashMap<>();

containerMap.put("1", lhMap1);
containerMap.put("2", lhMap2);

Then on your container you can call get()

containerMap.get("1"); // will give you lhMap1
containerMap.get("1").get("a"); // will return 'b'

Also, keySet() and values() are useful.

containerMap.keySet(); // will give you a Set<String>
containerMap.values(); // will give you a Collection<LinkedHashMap<String, String>>

Upvotes: 0

Related Questions