tipsy / j2html

Java to HTML generator. Enjoy typesafe HTML generation.
https://j2html.com/
Apache License 2.0
765 stars 136 forks source link

Add Stream<DomContent> variants of each and with #118

Closed snago closed 6 years ago

snago commented 6 years ago

The each-methods that takes a Collection or a Map and a Function or BiFunction are nice, but accepting Stream directly would be even more powerful.

each(filter(numbers, n -> n % 2 == 0), n -> li(n.toString()))

would become

each(numbers.stream().filter(n -> n % 2 == 0).map(n -> li(n.toString())))

Sure, that's not shorter but it means other stream functionality such as limit, flatMap, etc. won't have to be duplicated as TagCreator methods. E.g.:

each(numbers.stream().filter(n -> n % 2 == 0).limit(10).map(n -> li(n.toString())))
tipsy commented 6 years ago

That's a nice approach. Maybe the other methods should be deprecated in favor of this. Could you type of a few examples so I can compare?

snago commented 6 years ago

Yes, TagCreator.filter, TagCreator.each(Collection, Function) and TagCreator.each(Map, Function) can probably be deprecated in favor of TagCreator.each(Stream). I would keep TagCreator.each(Map, BiFunction) though, as that can be easier to use than having to deal with a stream of entries.

Here is the filter example from https://j2html.com/examples.html, rewritten to use the new each-method and with the employees sorted by name:

    body(
        div(attrs("#employees"),
            p("Some sibling element"),
            each(employees.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(Employee::getName))
                .map(employee -> div(attrs(".employee"),
                    h2(employee.getName()),
                    img().withSrc(employee.getImgPath()),
                    p(employee.getTitle())
                ))
            )
        )
    )
tipsy commented 6 years ago

Thanks! I'll merge this now and think about deprecating the other methods.