diff --git a/src/test/java/lambda/part3/exercise/Mapping.java b/src/test/java/lambda/part3/exercise/Mapping.java index c0a814a..56ec252 100644 --- a/src/test/java/lambda/part3/exercise/Mapping.java +++ b/src/test/java/lambda/part3/exercise/Mapping.java @@ -32,8 +32,11 @@ public List getList() { // [T] -> (T -> R) -> [R] // [T1, T2, T3] -> (T -> R) -> [R1, R2, R3] public MapHelper map(Function f) { - // TODO - throw new UnsupportedOperationException(); + final List result = new ArrayList<>(); + for (T element : list) { + result.add(f.apply(element)); + } + return new MapHelper<>(result); } // [T] -> (T -> [R]) -> [R] @@ -76,11 +79,9 @@ public void mapping() { final List mappedEmployees = new MapHelper<>(employees) - /* - .map(TODO) // change name to John .map(e -> e.withPerson(e.getPerson().withFirstName("John"))) - .map(TODO) // add 1 year to experience duration .map(e -> e.withJobHistory(addOneYear(e.getJobHistory()))) - .map(TODO) // replace qa with QA - * */ + .map(e -> e.withPerson(e.getPerson().withFirstName("John"))) + .map(e -> e.withJobHistory(addOneYear(e.getJobHistory()))) + .map(e -> e.withJobHistory(replaceQA(e.getJobHistory()))) .getList(); final List expectedResult = @@ -108,10 +109,28 @@ public void mapping() { assertEquals(mappedEmployees, expectedResult); } + private List replaceQA(List jobHistory) { + return new MapHelper<>(jobHistory) + .map(j -> j.getPosition().equals("qa") + ? j.withPosition("QA") + : j.withPosition(j.getPosition())) + .getList(); + } + + private List addOneYear(List jobHistory) { + return new MapHelper<>(jobHistory) + .map(j -> j.withDuration(j.getDuration() + 1)) + .getList(); + } + private static class LazyMapHelper { + private List list; + private Function function; public LazyMapHelper(List list, Function function) { + this.list = list; + this.function = function; } public static LazyMapHelper from(List list) { @@ -119,15 +138,19 @@ public static LazyMapHelper from(List list) { } public List force() { - // TODO - throw new UnsupportedOperationException(); + List result = new ArrayList<>(); + for (T element : list) { + result.add(function.apply(element)); + } + + return result; } public LazyMapHelper map(Function f) { - // TODO - throw new UnsupportedOperationException(); - } + return new LazyMapHelper<>(list, (function.andThen(f))); + + } } private static class LazyFlatMapHelper { @@ -165,8 +188,6 @@ public LazyFlatMapHelper flatMap(Function> f) { } } - - @Test public void lazy_mapping() { final List employees = @@ -193,6 +214,9 @@ public void lazy_mapping() { final List mappedEmployees = LazyMapHelper.from(employees) + .map(e -> e.withPerson(e.getPerson().withFirstName("John"))) + .map(e->e.withJobHistory(addOneYear(e.getJobHistory()))) + .map(e ->e.withJobHistory(replaceQA(e.getJobHistory()))) /* .map(TODO) // change name to John .map(TODO) // add 1 year to experience duration