Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use HashMap in Java velocity template with Example
43889 Views
HashMapForeachVelocityExample
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class HashMapForeachVelocityExample {
    public static void main(String args[]) throws Exception {
        Map<String,String> userDataMap = new HashMap<String,String>();
            userDataMap.put("1001", "Sarathy");
            userDataMap.put("1002", "Kumar");
            userDataMap.put("1003", "Raja");
            userDataMap.put("1004", "Gopal");
            
        VelocityEngine engine = new VelocityEngine();
        engine.init();
         
        Template template = engine.getTemplate("userinfo.vm");
         
        VelocityContext vc = new VelocityContext();
        vc.put("userDataMap", userDataMap);
         
        StringWriter writer = new StringWriter();
        template.merge(vc, writer);
         
        System.out.println(writer);
    }
}
Userinfo.vm 
User Details
------------
#foreach ($rno in $userDataMap.keySet())
Rno is. $rno; Name is $userDataMap[$rno] or Name is $userDataMap.get($rno)
#end
Output 
User Details
------------
Rno is. 1003; Name is Raja or Name is Raja
Rno is. 1004; Name is Gopal or Name is Gopal
Rno is. 1001; Name is Sarathy or Name is Sarathy
Rno is. 1002; Name is Kumar or Name is Kumar
Best Lessons of "Java Apache Velocity Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details