[stringtemplate-interest] Map usage

Terence Parr parrt at cs.usfca.edu
Wed Sep 24 17:18:04 PDT 2008


On Sep 24, 2008, at 12:36 PM, D. Frej wrote:

> Hi,
>
> here is the situation that I want to get solved: in Java I have an  
> array containing Integer (the Object, not the primitive type int).
>
> Integer[] ar = new Integer[7];
> ar[0] = 8;
> ar[1] = 3;
> ar[2] = 5;
> ar[3] = 8;
> ar[4] = 7;
> ar[5] = 5;
> ar[6] = 9;
>
> This array contains duplicates (on purpose). The output I want to  
> have - using stringtemplate - is the following
>
> 1	8	occurs in the array more than 1 time
> 2	3	
> 3	5	occurs in the array more than 1 time
> and so on
>
> Printing the array is easy. Using (Java code)
>
> StringTemplateGroup stGroup = new StringTemplateGroup("mygroup", "C:\ 
> \workspace");
> StringTemplate st = stGroup.getInstanceOf("jexample");
> st.setAttribute("numbers", ar);
> System.out.println(st.toString());
>
> and the template
>
> junitclass(numbers) ::= <<
> $numbers:{ a | $i$\t$a$ }$
>>>
>
> As far as I have seen in the documentation, there is no way that I  
> can call a method on a Java object. Since it is possible to retrieve  
> attributes one way to undermine this is to create a method in the  
> Java object starting with getXYZ() and print out object.xyz. Is it  
> correct that I cannot pass a parameter into the method from the  
> template? Equivalent to a call in Java like object.getXYZ(i).

Correct...there is no way to call a method with an argument...

> Did I understand correctly that the proposed way would be to create  
> a map containing the values of the array as keys (in the example 3,  
> 5, 7, 8, 9) and the value of the map is the number of occurances?  
> How would the code look alike?

You are probably incorrectly trying to do a computation in the  
template. I would suggest you do your histogram inside your model and  
then pushing the results rather than asking ST to compute frequencies.

>
>
> And: how can I find out if a certain key is in the map or not? E.g.  
> if I checked for the key '4' (if 4 is a key in the map), how can  
> print out some message stating that it "is not in the map"?

You can probably just test $m.key; null="default value if not in map"$  
or something like that.

Ter


More information about the stringtemplate-interest mailing list