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

This commit is contained in:
Robin Karlsson
2018-05-20 21:45:36 +02:00
committed by David
parent 764b5d7759
commit cd6e0084ef
3 changed files with 36 additions and 1 deletions

View File

@@ -18,6 +18,7 @@ import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TagCreator {
@@ -83,6 +84,17 @@ public class TagCreator {
return DomContentJoiner.join(" ", true, stringOrDomObjects);
}
/**
* Creates a DomContent object containing HTML elements from a stream.
* Intended usage: {@literal each(numbers.stream().map(n -> li(n.toString())))}
*
* @param stream the stream of DomContent elements
* @return DomContent containing elements from the stream
*/
public static DomContent each(Stream<DomContent> stream) {
return new ContainerTag(null).with(stream);
}
/**
* Creates a DomContent object containing HTML using a mapping function on a collection
* Intended usage: {@literal each(numbers, n -> li(n.toString()))}
@@ -93,7 +105,7 @@ public class TagCreator {
* @return DomContent containing mapped data {@literal (ex. docs: [li(1), li(2), li(3)])}
*/
public static <T> DomContent each(Collection<T> collection, Function<? super T, DomContent> mapper) {
return tag(null).with(collection.stream().map(mapper).collect(Collectors.toList()));
return tag(null).with(collection.stream().map(mapper));
}
public static <I, T> DomContent each(final Map<I, T> map, final Function<Entry<I, T>, DomContent> mapper) {

View File

@@ -4,6 +4,7 @@ import j2html.Config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ContainerTag extends Tag<ContainerTag> {
@@ -89,6 +90,18 @@ public class ContainerTag extends Tag<ContainerTag> {
}
/**
* Appends the DomContent-objects in the stream to the end of this element
*
* @param children Stream of DomContent-objects to be appended
* @return itself for easy chaining
*/
public ContainerTag with(Stream<DomContent> children) {
children.forEach(this::with);
return this;
}
/**
* Call with-method based on condition
* {@link #with(DomContent... children)}

View File

@@ -143,6 +143,16 @@ public class TagCreatorTest {
assertThat(j2htmlFilter.equals(javaFilter), is(true));
}
@Test
public void testEachWithStream() throws Exception {
final String j2htmlMap = ul().with(
li("Begin list"),
each(employeeMap.entrySet().stream().map(e -> li(e.getKey() + "-" + e.getValue().name)))
).render();
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li>1-Name 1</li><li>2-Name 2</li><li>3-Name 3</li></ul>"));
}
@Test
public void testAllTags() throws Exception {