JSP operation Map array collection

One, create a Map collection

<%@ page import="java.util.*"%>
<%
//创建Map集合
java.util.Map<String,String> map= new java.util.HashMap<String ,String>();
%>

Supplement: If the page does not reference import="java.util.*" , you need to add java.util. before the Map , that is,  java.util.Map

2. Add elements (data) to the Map collection

//添加元素
map.put("name","张三");
map.put("age",18);

3. Get the Map element according to the key name

//读取元素
map.get("name")

Fourth, traverse the Map collection

Method 1: Traverse key and value through Map.entrySet, and use entries to traverse in a for-each loop

for (java.util.Map.Entry<String,String> entry : map.entrySet()) { 
    out.println("<br>Key = " + entry.getKey() + ", Value = " + entry.getValue());  
}

Method 2: Traverse the key through Map.keySet and find the value through the key key (the traversal efficiency is relatively low, it is commonly used, and the value is obtained twice)

for (String key : map.keySet()) {  
    Object value = map.get(key);  
    out.println("<br>Key = " + key + ", Value = " + value); 
}

Method 3: If you only need the keys or values ​​in the map, you can traverse through Map.keySet or Map.values ​​instead of using entrySet, as follows:

//遍历map中的键
for (String key : map.keySet()) {  
    out.println("<br>Key = " + key);  
}  

//遍历map中的值
for (Object value : map.values()) {  
    out.println("<br>Value = " + value);  
}

Method 4: Use iterator to traverse key and value

//创建迭代器
java.util.Iterator<java.util.Map.Entry<String,String>> entries = map.entrySet().iterator(); 
//遍历
while (entries.hasNext()) {
    java.util.Map.Entry<String,Object> entry = entries.next(); 
    out.println("<br>Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}

Five, remove the elements of the Map collection

<%
//根据key键名移除Map集合元素
deleteMapItem(map,"name");
%>
<%!
/**
 * 根据key键名移除Map集合元素
 * map  Map集合
 * name key键名
 */
public void deleteMapItem(java.util.Map<String,Object> map,String name){
	Iterator<String> iterator = map.keySet().iterator();
	while (iterator.hasNext()) {
	    String key = iterator.next();
	    if (key.startsWith(name)) {
	        iterator.remove();
	    }
	}
}
%>

Note: the method function must be defined in <%!> Lane

Guess you like

Origin blog.csdn.net/qq15577969/article/details/112800726
Recommended