Uploaded image for project: 'Apache Freemarker'
  1. Apache Freemarker
  2. FREEMARKER-43

Consider adding a Java 8 Style forEach method to TemplateCollectionModel/TemplateSequenceModel

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Open
    • Minor
    • Resolution: Unresolved
    • 2.3.25-incubating
    • None
    • engine
    • None

    Description

      I have a lot of "tuple-like" types in my model. For example:

      class Tuple {
        int a;
        float b;
        String c;
      }
      

      In the template, i would like to iterate through the components of tuple using #list. To implement TemplateSequenceModel or TemplateCollectionModel, I basically need to create a temporary List object from the tuple, which seems unnecessary.

      Java 8 added a forEach model to java.lang.Iterable, which could be easily implemented for Tuple without temporary objects:

      // in Tuple
      void forEach(Consumer<Object> c) {
        c.accept(a);
        c.accept(b);
        c.accept(c);
      }
      

      Unfortunately, there is no such method in TemplateSequenceModel/TemplateCollectionModel.

      I propose to add such a method to the both classes and use this method in IteratorBlock instead of handcrafted iteration. This would allow to more efficient iteration for custom classes, while not imposing worse performance on "standard" collections/interfaces (these also provide forEach in java8).

      As this change would require java8, this API change would not break existing implementations of Template*Model, as forEach could be implemented as default interface method.

      I could provide a prototype patch if requested.

      Maybe as a separate bug, TemplateCollectionModel, TemplateSequenceModel should both inherit from a new TemplateIterableModel which only provides forEach.

      Attachments

        Activity

          People

            Unassigned Unassigned
            thomas001le Thomas Weidner
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated: