From 2389682d8ecc5668ac2e7e5b0003420e6d76092c Mon Sep 17 00:00:00 2001 From: Elena Georgievskaia Date: Tue, 11 Jul 2017 17:10:11 +0300 Subject: [PATCH 1/3] part2.1 --- .../part2/exercise/CollectorsExercise1.java | 93 +++++++++++++++---- 1 file changed, 75 insertions(+), 18 deletions(-) diff --git a/src/test/java/part2/exercise/CollectorsExercise1.java b/src/test/java/part2/exercise/CollectorsExercise1.java index 46b6765..58c0881 100755 --- a/src/test/java/part2/exercise/CollectorsExercise1.java +++ b/src/test/java/part2/exercise/CollectorsExercise1.java @@ -6,17 +6,13 @@ import org.junit.Test; import java.util.*; -import java.util.concurrent.ThreadLocalRandom; -import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collector; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; -import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.*; +import static org.junit.Assert.assertEquals; public class CollectorsExercise1 { @@ -53,16 +49,41 @@ public int getDuration() { // With the longest duration on single job private Map getCoolestByPosition(List employees) { - // First option - // Collectors.maxBy - // Collectors.collectingAndThen - // Collectors.groupingBy - - // Second option - // Collectors.toMap - // iterate twice: stream...collect(...).stream()... - // TODO - throw new UnsupportedOperationException(); + Map collect = employees.stream() + .flatMap( + this::toPersonPositionDuration + ) + .collect( + groupingBy( + PersonPositionDuration::getPosition, + collectingAndThen(maxBy(Comparator.comparing(PersonPositionDuration::getDuration)), p -> p.get().getPerson()) + ) + ); + + Map collect1 = employees.stream() + .flatMap(this::toPersonPositionDuration) + .collect(Collectors.toMap( + PersonPositionDuration::getPosition, + Function.identity(), + BinaryOperator.maxBy(Comparator.comparing(PersonPositionDuration::getDuration)) + )) + .entrySet().stream() + .collect( + toMap( + Map.Entry::getKey, + t -> t.getValue().getPerson() + ) + ); + + + assertEquals(collect, collect); + + return collect; + } + + private Stream toPersonPositionDuration(Employee employee) { + return employee.getJobHistory().stream() + .map(jobHistoryEntry -> new PersonPositionDuration(employee.getPerson(), jobHistoryEntry.getPosition(), jobHistoryEntry.getDuration())); } @Test @@ -75,8 +96,44 @@ public void getTheCoolestOne2() { // With the longest sum duration on this position // { John Doe, [{dev, google, 4}, {dev, epam, 4}] } предпочтительнее, чем { A B, [{dev, google, 6}, {QA, epam, 100}]} private Map getCoolestByPosition2(List employees) { - // TODO - throw new UnsupportedOperationException(); + return employees.stream() + .flatMap(this::toExclusivePersonPositionDuration) + .collect( + groupingBy( + PersonPositionDuration::getPosition, + collectingAndThen(maxBy(Comparator.comparing(PersonPositionDuration::getDuration)), p -> p.get().getPerson()) + ) + ); + /*.collect( + toMap( + PersonPositionDuration::getPosition, + Function.identity(), + (p1, p2) -> p1.getDuration() > p2.getDuration() ? p1 : p2 + ) + ).entrySet() + .stream() + .collect( + toMap( + Map.Entry::getKey, + e -> e.getValue().getPerson() + ) + );*/ + } + + private Stream toExclusivePersonPositionDuration(Employee employee) { + return employee.getJobHistory() + .stream() + .collect( + toMap(JobHistoryEntry::getPosition, + JobHistoryEntry::getDuration, + (d1, d2) -> d1 + d2 + ) + ) + .entrySet() + .stream() + .map( + entry -> new PersonPositionDuration(employee.getPerson(), entry.getKey(), entry.getValue()) + ); } private List getEmployees() { From 6b15bd66a5d07e02a1fe71c66943aff88a8bef15 Mon Sep 17 00:00:00 2001 From: sausageRoll Date: Wed, 12 Jul 2017 10:42:50 +0300 Subject: [PATCH 2/3] temp --- .../part2/exercise/CollectorsExercise2.java | 79 +++++++++++++------ 1 file changed, 56 insertions(+), 23 deletions(-) diff --git a/src/test/java/part2/exercise/CollectorsExercise2.java b/src/test/java/part2/exercise/CollectorsExercise2.java index 00fda00..6e15b7a 100755 --- a/src/test/java/part2/exercise/CollectorsExercise2.java +++ b/src/test/java/part2/exercise/CollectorsExercise2.java @@ -1,8 +1,5 @@ package part2.exercise; -import data.Employee; -import data.JobHistoryEntry; -import data.Person; import org.junit.Test; import java.util.*; @@ -16,7 +13,7 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.*; public class CollectorsExercise2 { @@ -31,20 +28,20 @@ private static String generateString() { .collect(Collectors.joining()); } - private static String[] generateStringArray(int length) { + private static String[] generateStringArray(final int length) { return Stream.generate(CollectorsExercise2::generateString) .limit(length) .toArray(String[]::new); } - public static String pickString(String[] array) { + private static String pickString(final String[] array) { return array[ThreadLocalRandom.current().nextInt(array.length)]; } public static class Key { private final String id; - public Key(String id) { + public Key(final String id) { this.id = id; } @@ -53,14 +50,13 @@ public String getId() { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - Key key = (Key) o; + final Key key = (Key) o; return id.equals(key.id); - } @Override @@ -72,7 +68,7 @@ public int hashCode() { public static class Value { private final String keyId; - public Value(String keyId) { + public Value(final String keyId) { this.keyId = keyId; } @@ -85,7 +81,7 @@ public static class Pair { private final Key key; private final Value value; - public Pair(Key key, Value value) { + public Pair(final Key key, final Value value) { this.key = key; this.value = value; } @@ -99,7 +95,7 @@ public Value getValue() { } } - public static List generatePairs(int idCount, int length) { + public static List generatePairs(final int idCount, final int length) { final String[] ids = generateStringArray(idCount); return Stream.generate(() -> new Pair(new Key(pickString(ids)), new Value(pickString(ids)))) @@ -112,7 +108,7 @@ private static class SubResult { private final Map> knownKeys; private final Map> valuesWithoutKeys; - public SubResult(Map> subResult, Map> knownKeys, Map> valuesWithoutKeys) { + public SubResult(final Map> subResult, final Map> knownKeys, final Map> valuesWithoutKeys) { this.subResult = subResult; this.knownKeys = knownKeys; this.valuesWithoutKeys = valuesWithoutKeys; @@ -139,7 +135,7 @@ public MapPair() { this(new HashMap<>(), new HashMap<>()); } - public MapPair(Map keyById, Map> valueById) { + public MapPair(final Map keyById, final Map> valueById) { this.keyById = keyById; this.valueById = valueById; } @@ -154,9 +150,9 @@ public Map> getValueById() { } private static > - BinaryOperator mapMerger(BinaryOperator mergeFunction) { + BinaryOperator mapMerger(final BinaryOperator mergeFunction) { return (m1, m2) -> { - for (Map.Entry e : m2.entrySet()) { + for (final Map.Entry e : m2.entrySet()) { m1.merge(e.getKey(), e.getValue(), mergeFunction); } return m1; @@ -170,7 +166,32 @@ public void collectKeyValueMap() { // В два прохода // final Map keyMap1 = pairs.stream()... + final Map idToKey = pairs.stream() + .collect( + toMap( + pair -> pair.getKey().getId(), + Pair::getKey + ) + ); + // final Map> valuesMap1 = pairs.stream()... + final Map> result = pairs.stream() + .collect(groupingBy( + pair -> pair.getValue().getKeyId(), + collectingAndThen(mapping(Pair::getValue, toList()), Function.identity()) + )) + .entrySet().stream() + .collect( + toMap( + pair -> idToKey.get(pair.getKey()), + Map.Entry::getValue, + (l1, l2) -> { + l1.addAll(l2); + return l1; + } + ) + ); + // В каждом Map.Entry id ключа должно совпадать с keyId для каждого значения в списке // final Map> keyValuesMap1 = valueMap1.entrySet().stream()... @@ -180,20 +201,32 @@ public void collectKeyValueMap() { .collect(new Collector() { @Override public Supplier supplier() { - // TODO - throw new UnsupportedOperationException(); + return MapPair::new; } @Override public BiConsumer accumulator() { - // TODO add key and value to maps - throw new UnsupportedOperationException(); + return (mapPair, pair) -> { + mapPair.getKeyById().put(pair.getKey().getId(),pair.getKey()); + mapPair.getValueById().merge( + pair.getValue().getKeyId(), + Collections.singletonList(pair.getValue()), + this::listMerger + ); + }; + } + + private List listMerger(List values, List values1) { + values.addAll(values1); + return values; } @Override public BinaryOperator combiner() { - // TODO use mapMerger - throw new UnsupportedOperationException(); + /*return (m1, m2) -> { + mapMerger((Key k1, Key k2) -> k1.equals(k2) ? k1 : k2).apply(m1.getKeyById(),m2.getKeyById()); + }*/ + //return mapMerger(this::listMerger); } @Override From a480bfb821837853a51622da5cb35146674b2a0e Mon Sep 17 00:00:00 2001 From: Aleksandr Petukhov Date: Wed, 12 Jul 2017 16:22:42 +0300 Subject: [PATCH 3/3] ex 2 completed --- .../part2/exercise/CollectorsExercise2.java | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/test/java/part2/exercise/CollectorsExercise2.java b/src/test/java/part2/exercise/CollectorsExercise2.java index 6e15b7a..cc7a26e 100755 --- a/src/test/java/part2/exercise/CollectorsExercise2.java +++ b/src/test/java/part2/exercise/CollectorsExercise2.java @@ -175,7 +175,7 @@ public void collectKeyValueMap() { ); // final Map> valuesMap1 = pairs.stream()... - final Map> result = pairs.stream() + final Map> keyValuesMap1 = pairs.stream() .collect(groupingBy( pair -> pair.getValue().getKeyId(), collectingAndThen(mapping(Pair::getValue, toList()), Function.identity()) @@ -207,7 +207,7 @@ public Supplier supplier() { @Override public BiConsumer accumulator() { return (mapPair, pair) -> { - mapPair.getKeyById().put(pair.getKey().getId(),pair.getKey()); + mapPair.getKeyById().put(pair.getKey().getId(), pair.getKey()); mapPair.getValueById().merge( pair.getValue().getKeyId(), Collections.singletonList(pair.getValue()), @@ -223,10 +223,17 @@ private List listMerger(List values, List values1) { @Override public BinaryOperator combiner() { - /*return (m1, m2) -> { - mapMerger((Key k1, Key k2) -> k1.equals(k2) ? k1 : k2).apply(m1.getKeyById(),m2.getKeyById()); - }*/ - //return mapMerger(this::listMerger); + return (p1, p2) -> { + BinaryOperator> toKey = mapMerger((k1, k2) -> k1); + BinaryOperator>> toValues = mapMerger((v1, v2) -> { + v1.addAll(v2); + return v1; + }); + + toKey.apply(p1.getKeyById(),p2.getKeyById()); + toValues.apply(p1.getValueById(),p2.getValueById()); + return new MapPair(p1.getKeyById(),p2.getValueById()); + }; } @Override @@ -245,15 +252,23 @@ public Set characteristics() { final Map keyMap2 = res2.getKeyById(); final Map> valuesMap2 = res2.getValueById(); - // final Map> keyValuesMap2 = valueMap2.entrySet().stream()... - + final Map> keyValuesMap2 = valuesMap2.entrySet().stream() + .collect( + toMap( + pair -> idToKey.get(pair.getKey()), + Map.Entry::getValue, + (l1, l2) -> { + l1.addAll(l2); + return l1; + } + ) + ); // Получение результата сразу: final SubResult res3 = pairs.stream() .collect(new Collector() { @Override public Supplier supplier() { - // TODO throw new UnsupportedOperationException(); }