Skip to content

Commit b18459c

Browse files
authored
Bifunction each (#191)
Adding TagCreator.each() method to provide access to the collection index.
1 parent aa8fb7c commit b18459c

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

library/src/main/java/j2html/TagCreator.java

+19-5
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,8 @@
1111
import j2html.tags.UnescapedText;
1212
import j2html.tags.specialized.*;
1313

14-
import java.util.Collection;
15-
import java.util.List;
16-
import java.util.Map;
14+
import java.util.*;
1715
import java.util.Map.Entry;
18-
import java.util.Objects;
19-
import java.util.Optional;
2016
import java.util.function.BiFunction;
2117
import java.util.function.Function;
2218
import java.util.function.Predicate;
@@ -122,6 +118,24 @@ public static <T> DomContent each(Collection<T> collection, Function<? super T,
122118
return tag(null).with(collection.stream().map(mapper));
123119
}
124120

121+
/**
122+
* Creates a DomContent object containing HTML using a mapping BiFunction on a collection
123+
* Intended usage: {@literal each(names, (index, name) -> li(index + " " + name))}
124+
*
125+
* @param <T> The derived generic parameter type
126+
* @param collection the collection to iterate over, ex: a list of values [ "Tom", "Dick", "Harry" ]
127+
* @param mapper the mapping BiFunction, ex: {@literal "(index, name) -> li(index + " " + name)"}
128+
* @return DomContent containing mapped data {@literal (ex. docs: [li(0 Tom), li(1 Dick), li(2 Harry)])}
129+
*/
130+
public static <T> DomContent each(Collection<T> collection, BiFunction<Integer, ? super T, DomContent> mapper) {
131+
ContainerTag<?> dom = tag(null);
132+
int i = 0;
133+
for(T t : collection){
134+
dom.with(mapper.apply(i++, t));
135+
}
136+
return dom;
137+
}
138+
125139
public static <I, T> DomContent each(final Map<I, T> map, final Function<Entry<I, T>, DomContent> mapper) {
126140
return each(map.entrySet().stream().map(mapper));
127141
}

library/src/test/java/j2html/tags/TagCreatorTest.java

+14
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,20 @@ public void testEach() throws Exception {
104104
assertThat(j2htmlMap.equals(javaMap), is(true));
105105
}
106106

107+
@Test
108+
public void each_provides_the_collection_index_to_bifunctions(){
109+
assertThat(
110+
table(
111+
each(employees, (index, employee) -> tr(
112+
td(Integer.toString(index)),
113+
td(employee.name),
114+
td(employee.title)
115+
))
116+
).render(),
117+
is("<table><tr><td>0</td><td>Name 1</td><td>Title 1</td></tr><tr><td>1</td><td>Name 2</td><td>Title 2</td></tr><tr><td>2</td><td>Name 3</td><td>Title 3</td></tr></table>")
118+
);
119+
}
120+
107121
@Test
108122
public void testEachWithMap() {
109123
final String j2htmlMap = ul().with(

0 commit comments

Comments
 (0)