8

In StringTemplate 4, the default behavior for iteration is to iterate over the keys instead of the values, which was the behavior in version 3.

I can not find the syntax for how to iterate over the keys and values at the same time for version 4.

Can someone post an example of the syntax?

JoshDM
  • 4,939
  • 7
  • 43
  • 72

2 Answers2

11

You can use indirect property referencing to get the value for the key in the current iteration. Is this what you mean?

<myMap.keys:{k | <k> maps to <myMap.(k)>}; separator="\n">

prints:

Jake maps to Dog
Finn maps to Human
Andy Stabler
  • 1,309
  • 1
  • 15
  • 19
0

Sample input :

List<String> myList  =  new ArrayList<>();
myList.add("k1");
myList.add("k2");
myList.add("k3");


Map<String,String> myMap =  new HashMap<>();
myMap.put("k1", "v1");
myMap.put("k2", "v2");
myMap.put("k3", "v3");
  • Prints key-value pairs in random order.

       $myMap.keys:{key | $key$  maps to $myMap.(key)$ }; separator="\n"$
    

Output:(random order)

 k3 maps to v3
 k1 maps to v1
 k2 maps to v2
  • Prints key-value pairs in-order defined by list.

      $myList:{item | $item$  maps to $myMap.(item)$ }; separator="\n"$
    

Output:(ordered)

 k1 maps to v1
 k2 maps to v2
 k3 maps to v3
Sanjiv
  • 1,795
  • 1
  • 29
  • 45