遍历Map取值

阅读量: 150 编辑

遍历Map取值

一、语法

<#if map??>
    <#list map?keys as key>
        ${key} : ${map[key]}
    </#list>
</#if>

<#if map??>
    <#list map as key, item>
        ${key} : ${item}
    </#list>
</#if>

注意:如果key是整数不可以这样使用

二、代码实战

代码的详细解读,可以参考视频教程

S12Controller.java

package com.qicong.sboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * User: 祁大聪
 */
@Controller
public class S12Controller {

    @GetMapping("/s12")
    public ModelAndView s12(){
        ModelAndView mv = new ModelAndView();

        Map<String,Person> map = new LinkedHashMap<String,Person>();
        for(int i = 0; i < 10; i++){
            Person p = new Person();
            p.setName("sanNi-" + i);
            p.setAge(20 + i);
            p.setHeight(170);
            map.put("key-" + i, p);
        }

        mv.addObject("personMap",map);
        return mv;
    }
}


s12.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <#if personMap??>
            <#list personMap?keys as key>
                ${key} , ${(personMap[key].name)!} , ${(personMap[key].age)!}<br/>
            </#list>
        </#if>
    </body>
</html>