Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use Nested for loop in Java velocity with Example
20364 Views
NestedForEachVelocityExample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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