Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use Nested for loop in Java velocity with Example
18020 Views
NestedForEachVelocityExample
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class NestedForEachVelocityExample {
    public static void main(String args[]){
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        
        Template template = engine.getTemplate("velocitytemplate.vm");
        
        Map<String,List<String>> userNamesByCompany = new HashMap<String, List<String>>();
        {
            List<String> userNames = new ArrayList<String>();
                userNames.add("Raja");
                userNames.add("Roja");
                
            userNamesByCompany.put("android", userNames);
        }
        {
            List<String> userNames = new ArrayList<String>();
                userNames.add("Peter");
                userNames.add("John");
                
            userNamesByCompany.put("microsoft", userNames);
        }
        
        VelocityContext context = new VelocityContext();
            context.put("userNamesByCompany", userNamesByCompany);
            
        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        
        System.out.println(sw.toString());
    }
}
Velocitytemplate.vm 
#foreach ($company_name in $userNamesByCompany.keySet())
$company_name.toUpperCase() employees:
#foreach ($userName in $userNamesByCompany.get($company_name))
$userName
#end

#end
Output 
ANDROID employees:
Raja
Roja

MICROSOFT employees:
Peter
John
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