How can I iterate over the keys and values of a String Template 4 Map?
Asked Answered
E

2

9

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?

Eden answered 25/8, 2015 at 19:54 Comment(0)
S
12

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
Salisbarry answered 26/8, 2015 at 8:20 Comment(1)
bonus rep for the Adventure Time reference!Eden
B
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
Bebop answered 5/2, 2021 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.