Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 52 additions & 15 deletions src/test/java/part2/exercise/CollectorsExercise1.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,19 @@
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 {

@Test
public void getTheCoolestOne() {
final Map<String, Person> coolestByPosition = getCoolestByPosition(getEmployees());
final Map<String, Person> coolestByPositionFirst = getCoolestByPositionFirst(getEmployees());
final Map<String, Person> coolestByPositionSecond = getCoolestByPositionSecond(getEmployees());

coolestByPosition.forEach((position, person) -> System.out.println(position + " -> " + person));
assertEquals(coolestByPositionFirst, coolestByPositionSecond);
}

private static class PersonPositionDuration {
Expand Down Expand Up @@ -52,17 +46,40 @@ public int getDuration() {
}

// With the longest duration on single job
private Map<String, Person> getCoolestByPosition(List<Employee> employees) {
private Map<String, Person> getCoolestByPositionFirst(List<Employee> employees) {
// First option
// Collectors.maxBy
// Collectors.collectingAndThen
// Collectors.groupingBy
// TODO
return employees.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonPositionDuration(e.getPerson(), j.getPosition(), j.getDuration())))
.collect(
groupingBy(
PersonPositionDuration::getPosition,
collectingAndThen(
maxBy(Comparator.comparingInt(PersonPositionDuration::getDuration)),
o -> o.orElseThrow(IllegalStateException::new).getPerson()
)
)
);
}

private Map<String, Person> getCoolestByPositionSecond(List<Employee> employees) {
// Second option
// Collectors.toMap
// iterate twice: stream...collect(...).stream()...
// TODO
throw new UnsupportedOperationException();
return employees.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonPositionDuration(e.getPerson(), j.getPosition(), j.getDuration())))
.collect(toMap(
PersonPositionDuration::getPosition,
o -> new PersonPositionDuration(o.getPerson(), null, o.getDuration()),
(p1, p2) -> p1.getDuration() > p2.getDuration() ? p1 : p2
)).entrySet().stream()
.collect(toMap(Map.Entry::getKey, o -> o.getValue().getPerson()));
}

@Test
Expand All @@ -76,7 +93,27 @@ public void getTheCoolestOne2() {
// { John Doe, [{dev, google, 4}, {dev, epam, 4}] } предпочтительнее, чем { A B, [{dev, google, 6}, {QA, epam, 100}]}
private Map<String, Person> getCoolestByPosition2(List<Employee> employees) {
// TODO
throw new UnsupportedOperationException();
return employees.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonPositionDuration(e.getPerson(), j.getPosition(), j.getDuration())))
.collect(
groupingBy(
PersonPositionDuration::getPosition,
collectingAndThen(
groupingBy(
PersonPositionDuration::getPerson,
summingInt(PersonPositionDuration::getDuration)
),
m -> {
Map.Entry<Person, Integer> maxEntry = null;
for (Map.Entry<Person, Integer> entry : m.entrySet())
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
maxEntry = entry;
return maxEntry.getKey();
}
)
)
);
}

private List<Employee> getEmployees() {
Expand Down Expand Up @@ -151,7 +188,7 @@ private List<Employee> getEmployees() {
new Employee(
new Person("Bob", "White", 31),
Collections.singletonList(
new JobHistoryEntry(6, "QA", "epam")
new JobHistoryEntry(10, "QA", "epam")
))
);
}
Expand Down
128 changes: 100 additions & 28 deletions src/test/java/part2/exercise/CollectorsExercise2.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package part2.exercise;

import data.Employee;
import data.JobHistoryEntry;
import data.Person;
import org.junit.Test;

import java.util.*;
Expand All @@ -12,11 +9,11 @@
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 CollectorsExercise2 {

Expand All @@ -28,7 +25,7 @@ private static String generateString() {
return IntStream.range(0, length)
.mapToObj(letters::charAt)
.map(Object::toString)
.collect(Collectors.joining());
.collect(joining());
}

private static String[] generateStringArray(int length) {
Expand Down Expand Up @@ -99,20 +96,26 @@ public Value getValue() {
}
}

public static List<Pair> generatePairs(int idCount, int length) {
public static Set<Pair> generatePairs(int idCount, int length) {
final String[] ids = generateStringArray(idCount);

return Stream.generate(() -> new Pair(new Key(pickString(ids)), new Value(pickString(ids))))
.limit(length)
.collect(toList());
.collect(toSet());
}

private static class SubResult {
private final Map<Key, List<Value>> subResult;
private final Map<String, List<Key>> knownKeys;
private final Map<String, Key> knownKeys;
private final Map<String, List<Value>> valuesWithoutKeys;

public SubResult(Map<Key, List<Value>> subResult, Map<String, List<Key>> knownKeys, Map<String, List<Value>> valuesWithoutKeys) {
public SubResult(Map<Key, List<Value>> subResult) {
this.subResult = subResult;
this.knownKeys = null;
this.valuesWithoutKeys = null;
}

public SubResult(Map<Key, List<Value>> subResult, Map<String, Key> knownKeys, Map<String, List<Value>> valuesWithoutKeys) {
this.subResult = subResult;
this.knownKeys = knownKeys;
this.valuesWithoutKeys = valuesWithoutKeys;
Expand All @@ -126,7 +129,7 @@ public Map<String, List<Value>> getValuesWithoutKeys() {
return valuesWithoutKeys;
}

public Map<String, List<Key>> getKnownKeys() {
public Map<String, Key> getKnownKeys() {
return knownKeys;
}
}
Expand All @@ -135,22 +138,34 @@ private static class MapPair {
private final Map<String, Key> keyById;
private final Map<String, List<Value>> valueById;

public MapPair() {
MapPair() {
this(new HashMap<>(), new HashMap<>());
}

public MapPair(Map<String, Key> keyById, Map<String, List<Value>> valueById) {
MapPair(Map<String, Key> keyById, Map<String, List<Value>> valueById) {
this.keyById = keyById;
this.valueById = valueById;
}

public Map<String, Key> getKeyById() {
Map<String, Key> getKeyById() {
return keyById;
}

public Map<String, List<Value>> getValueById() {
Map<String, List<Value>> getValueById() {
return valueById;
}

void put(Pair p) {
keyById.put(p.getKey().getId(), p.getKey());
final ArrayList<Value> value = new ArrayList<>();
value.add(p.getValue());
valueById.merge(p.getValue().getKeyId(),
value,
(l1, l2) -> {
l1.addAll(l2);
return l1;
});
}
}

private static <K, V, M extends Map<K, V>>
Expand All @@ -165,35 +180,59 @@ BinaryOperator<M> mapMerger(BinaryOperator<V> mergeFunction) {

@Test
public void collectKeyValueMap() {
final List<Pair> pairs = generatePairs(10, 100);
final Set<Pair> pairs = generatePairs(10, 100);

// В два прохода
// final Map<String, Key> keyMap1 = pairs.stream()...

// final Map<String, List<Value>> valuesMap1 = pairs.stream()...
final Map<String, Key> keyMap1 = pairs.stream()
.collect(toMap(o -> o.getKey().getId(), Pair::getKey, (k1, k2) -> k1));

final Map<String, List<Value>> valuesMap1 = pairs.stream()
.collect(toMap(
o -> o.getValue().getKeyId(),
t -> {
final ArrayList<Value> values = new ArrayList<>();
values.add(t.getValue());
return values;
},
(l1, l2) -> {
l1.addAll(l2);
return l1;
}
));

// В каждом Map.Entry id ключа должно совпадать с keyId для каждого значения в списке
// final Map<Key, List<Value>> keyValuesMap1 = valueMap1.entrySet().stream()...
final Map<Key, List<Value>> keyValuesMap1 = valuesMap1.entrySet().stream()
.collect(toMap(o -> keyMap1.get(o.getKey()), Map.Entry::getValue));

// В 1 проход в 2 Map с использованием MapPair и mapMerger
final MapPair res2 = pairs.stream()
.collect(new Collector<Pair, MapPair, MapPair>() {
@Override
public Supplier<MapPair> supplier() {
// TODO
throw new UnsupportedOperationException();
return MapPair::new;
}

@Override
public BiConsumer<MapPair, Pair> accumulator() {
// TODO add key and value to maps
throw new UnsupportedOperationException();
return MapPair::put;
}

@Override
public BinaryOperator<MapPair> combiner() {
// TODO use mapMerger
throw new UnsupportedOperationException();
return (mapPair, mapPair2) -> {
BinaryOperator<Map<String, Key>> keyMerger = mapMerger((v1, v2) -> v1);
keyMerger.apply(mapPair.getKeyById(), mapPair2.getKeyById());
BinaryOperator<Map<String, List<Value>>> valueMerger =
mapMerger((v1, v2) -> {
v1.addAll(v2);
return v1;
});
valueMerger.apply(mapPair.getValueById(), mapPair2.getValueById());
return mapPair;
};
}

@Override
Expand All @@ -212,7 +251,8 @@ public Set<Characteristics> characteristics() {
final Map<String, Key> keyMap2 = res2.getKeyById();
final Map<String, List<Value>> valuesMap2 = res2.getValueById();

// final Map<Key, List<Value>> keyValuesMap2 = valueMap2.entrySet().stream()...
final Map<Key, List<Value>> keyValuesMap2 = valuesMap1.entrySet().stream()
.collect(toMap(o -> keyMap1.get(o.getKey()), Map.Entry::getValue));

// Получение результата сразу:

Expand All @@ -221,25 +261,54 @@ public Set<Characteristics> characteristics() {
@Override
public Supplier<SubResult> supplier() {
// TODO
throw new UnsupportedOperationException();
return () -> new SubResult(new HashMap<>(), new HashMap<>(), new HashMap<>());
}

@Override
public BiConsumer<SubResult, Pair> accumulator() {
// TODO add key to map, then check value.keyId and add it to one of maps
throw new UnsupportedOperationException();
return (subResult, pair) -> {
subResult.getKnownKeys().put(
pair.getKey().getId(),
pair.getKey());
final Map<String, List<Value>> values =
subResult.getValuesWithoutKeys();
if (values.containsKey(pair.getValue().getKeyId()))
values.get(pair.getValue().getKeyId())
.add(pair.getValue());
else {
List<Value> value = new ArrayList<>();
value.add(pair.getValue());
values.put(
pair.getValue().getKeyId(),
value);
}
};
}

@Override
public BinaryOperator<SubResult> combiner() {
// TODO use mapMerger, then check all valuesWithoutKeys
throw new UnsupportedOperationException();
return (subResult1, subResult2) -> {
BinaryOperator<Map<String, Key>> keyMerger = mapMerger((v1, v2) -> v1);
keyMerger.apply(subResult1.getKnownKeys(), subResult2.getKnownKeys());
BinaryOperator<Map<String, List<Value>>> valueMerger =
mapMerger((v1, v2) -> {
v1.addAll(v2);
return v1;
});
valueMerger.apply(subResult1.getValuesWithoutKeys(), subResult2.getValuesWithoutKeys());
return subResult1;
};
}

@Override
public Function<SubResult, SubResult> finisher() {
// TODO use mapMerger, then check all valuesWithoutKeys
throw new UnsupportedOperationException();
final Function<SubResult, Map<Key, List<Value>>> getResult =
subResult -> subResult.getValuesWithoutKeys().entrySet().stream()
.collect(toMap(o -> subResult.getKnownKeys().get(o.getKey()), Map.Entry::getValue));
return subResult -> new SubResult(getResult.apply(subResult));
}

@Override
Expand All @@ -251,6 +320,9 @@ public Set<Characteristics> characteristics() {

final Map<Key, List<Value>> keyValuesMap3 = res3.getSubResult();

assertEquals(keyValuesMap1, keyValuesMap2);
assertEquals(keyValuesMap1, keyValuesMap3);

// compare results
}

Expand Down
3 changes: 2 additions & 1 deletion src/test/java/part3/exercise/CollectorCombination.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collector;

Expand Down Expand Up @@ -46,7 +47,7 @@ public void collectKeyValueMap() {
// .collect(new Collector<Pair, MapPair, MapPair>() {

// Перепишите решение в слещующем виде:
final List<CollectorsExercise2.Pair> pairs = CollectorsExercise2.generatePairs(10, 100);
final Set<CollectorsExercise2.Pair> pairs = CollectorsExercise2.generatePairs(10, 100);

final Pair<Map<String, Key>, Map<String, List<Value>>> res2 = pairs.stream()
.collect(
Expand Down