Java 根据 JSTL 的键从 hashmap 中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18756463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:47:11  来源:igfitidea点击:

Get value from hashmap based on key to JSTL

javajsphashmapjstl

提问by newbie

I want to get the value of HashMapbased on key.

我想获得HashMap基于键的值。

HashMap<String, ArrayList<String>> map 
    = new HashMap<String, ArrayList<String>>();
ArrayList<String> arrayList = new ArrayList<String>();

map.put("key", arrayList);
request.setAttribute("key", map);

What i did is

我所做的是

<c:forEach var="map" items="${requestScope.key}">
    <c:forEach var="hash" items="${map.value}">
        <option><c:out value="${hash}"/></option>
    </c:forEach>
</c:forEach>

But it seems it's printing everything, what i want to do is to get the value depends on key like: hash.keyor something

但似乎它正在打印所有内容,我想要做的是获取取决于键的值,例如:hash.key或其他东西

UPDATE:
I did something like this but it still doesn't work

更新:
我做了这样的事情,但它仍然不起作用

<c:forEach var="map" items="${requestScope.key}">
    <c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
    </c:forEach>
</c:forEach>

and the StackTrace: Property 'External' not found on type java.util.HashMap$Entry
I'm pretty sure that there is really that kind of key.

和 StackTrace:Property 'External' not found on type java.util.HashMap$Entry
我很确定真的有那种密钥。

采纳答案by jason

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

如果您要做的只是获取地图中单个条目的值,则根本不需要遍历任何集合。稍微简化 gautum 的响应,您可以获得命名映射条目的值,如下所示:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

其中 'map' 是集合,'key' 是您尝试为其提取值的字符串键。

回答by Gautam

could you please try below code

你能试试下面的代码吗

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

回答by MR AND

I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on

我对上面提到的解决方案有疑问,因为指定字符串键会给我 javax.el.PropertyNotFoundException。下面显示的代码对我有用。在这个我使用状态来计算每个循环的索引并显示我感兴趣的索引值

<c:forEach items="${requestScope.key}"  var="map" varStatus="status" >
    <c:if test="${status.index eq 1}">
        <option><c:out value=${map.value}/></option>
    </c:if>
</c:forEach>