Skip to content

Commit 764b5d7

Browse files
mwanjitipsy
authored andcommitted
Add TagCreator::each(Map, BiFunction) (#115)
1 parent d9c4963 commit 764b5d7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/main/java/j2html/TagCreator.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import java.util.Map.Entry;
1515
import java.util.Objects;
1616
import java.util.Optional;
17+
import java.util.function.BiFunction;
1718
import java.util.function.Function;
1819
import java.util.function.Predicate;
1920
import java.util.stream.Collectors;
@@ -99,6 +100,20 @@ public static <I, T> DomContent each(final Map<I, T> map, final Function<Entry<I
99100
return rawHtml(map.entrySet().stream().map(mapper.andThen(DomContent::render)).collect(Collectors.joining()));
100101
}
101102

103+
/**
104+
* Creates a DomContent object containing HTML using a mapping function on a map
105+
* Intended usage: {@literal each(idsToNames, (id, name) -> li(id + " " + name))}
106+
*
107+
* @param <I> The type of the keys
108+
* @param <T> The type of the values
109+
* @param map the map to iterate over, ex: a map of values { 1: "Tom", 2: "Dick", 3: "Harry" }
110+
* @param mapper the mapping function, ex: {@literal "(id, name) -> li(id + " " + name)"}
111+
* @return DomContent containing mapped data {@literal (ex. docs: [li(1 Tom), li(2 Dick), li(3 Harry)])}
112+
*/
113+
public static <I, T> DomContent each(final Map<I, T> map, final BiFunction<I, T, DomContent> mapper) {
114+
return rawHtml(map.entrySet().stream().map(entry -> mapper.andThen(DomContent::render).apply(entry.getKey(), entry.getValue())).collect(Collectors.joining()));
115+
}
116+
102117
/**
103118
* Filters a collection to a list, to be used with {@link j2html.TagCreator#each}
104119
* Intended usage: {@literal each(filter(numbers, n -> n % 2 == 0), n -> li(n.toString()))}

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,16 @@ public void testEachWithMap() {
113113
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li>1-Name 1</li><li>2-Name 2</li><li>3-Name 3</li></ul>"));
114114
}
115115

116+
@Test
117+
public void testEachWithMapAndBiFunction() {
118+
final String j2htmlMap = ul().with(
119+
li("Begin list"),
120+
each(employeeMap, (id, employee) -> li(id + "-" + employee.name))
121+
).render();
122+
123+
assertThat(j2htmlMap, is("<ul><li>Begin list</li><li>1-Name 1</li><li>2-Name 2</li><li>3-Name 3</li></ul>"));
124+
}
125+
116126
@Test
117127
public void testFilter() throws Exception {
118128
String j2htmlFilter = ul().with(

0 commit comments

Comments
 (0)