Let each() take Map in addition to Collection (#110)

* add support for maps for 'each' method.

* add missing imports.
This commit is contained in:
Matthias
2018-04-16 20:11:37 +02:00
committed by David
parent 62cafb9b31
commit f212895eb2
2 changed files with 27 additions and 0 deletions

View File

@@ -10,6 +10,8 @@ import j2html.tags.Text;
import j2html.tags.UnescapedText;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
@@ -93,6 +95,10 @@ public class TagCreator {
return rawHtml(collection.stream().map(mapper.andThen(DomContent::render)).collect(Collectors.joining()));
}
public static <I, T> DomContent each(final Map<I, T> map, final Function<Entry<I, T>, DomContent> mapper) {
return rawHtml(map.entrySet().stream().map(mapper.andThen(DomContent::render)).collect(Collectors.joining()));
}
/**
* Filters a collection to a list, to be used with {@link j2html.TagCreator#each}
* Intended usage: {@literal each(filter(numbers, n -> n % 2 == 0), n -> li(n.toString()))}

View File

@@ -2,9 +2,12 @@ package j2html.tags;
import j2html.Config;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static j2html.TagCreator.*;
@@ -18,6 +21,14 @@ public class TagCreatorTest {
List<Employee> employees = Arrays.asList(new Employee(1, "Name 1", "Title 1"), new Employee(2, "Name 2", "Title 2"), new Employee(3, "Name 3", "Title 3"));
Map<Integer, Employee> employeeMap = new HashMap<>();
@Before
public void setUp() {
employeeMap.put(1, new Employee(1, "Name 1", "Title 1"));
employeeMap.put(2, new Employee(2, "Name 2", "Title 2"));
employeeMap.put(3, new Employee(3, "Name 3", "Title 3"));
}
@Test
public void testDocument() throws Exception {
@@ -92,6 +103,16 @@ public class TagCreatorTest {
assertThat(j2htmlMap.equals(javaMap), is(true));
}
@Test
public void testEachWithMap() {
final String j2htmlMap = ul().with(
li("Begin list"),
each(employeeMap, entry -> li(entry.getKey() + "-" + entry.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 testFilter() throws Exception {
String j2htmlFilter = ul().with(