Skip to content

Golubev Nikita - Part2 #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
5 changes: 3 additions & 2 deletions src/main/java/data/Generator.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public static Employee generateEmployee() {
}

public static List<Employee> generateEmployeeList() {
// TODO
throw new UnsupportedOperationException();
return Stream.generate(Generator::generateEmployee)
.limit(15)
.collect(toList());
}
}
90 changes: 85 additions & 5 deletions src/test/java/part2/exercise/CollectorsExercise1.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public class CollectorsExercise1 {
@Test
public void getTheCoolestOne() {
final Map<String, Person> coolestByPosition = getCoolestByPosition(getEmployees());

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

Expand Down Expand Up @@ -61,8 +60,78 @@ private Map<String, Person> getCoolestByPosition(List<Employee> employees) {
// Second option
// Collectors.toMap
// iterate twice: stream...collect(...).stream()...
// TODO
throw new UnsupportedOperationException();
final Map<String,Person> result;

employees.stream()
.flatMap(CollectorsExercise1::employeeInfo)
.collect(Collectors.groupingBy(PersonPositionDuration::getPosition, Collectors.collectingAndThen(
Collectors.maxBy(
Comparator.comparingInt(PersonPositionDuration::getDuration)),
info -> info.get().getPerson())));
employees.stream()
.flatMap(CollectorsExercise1::employeeInfo)
.collect(new Collector<PersonPositionDuration, Map<String,PersonPositionDuration>, Map<String,Person>>() {
@Override
public Supplier<Map<String, PersonPositionDuration>> supplier() {
return HashMap::new;
}

@Override
public BiConsumer<Map<String, PersonPositionDuration>, PersonPositionDuration> accumulator() {
return (map, info) -> map.merge(
info.getPosition(),
info,
(ppd1,ppd2) -> ppd2.getDuration() > ppd1.getDuration() ? ppd2 : ppd1);
}

@Override
public BinaryOperator<Map<String, PersonPositionDuration>> combiner() {
return (map1,map2) -> {
for (PersonPositionDuration info : map2.values()){
PersonPositionDuration mapInfo = map1.get(info.getPosition());
if (mapInfo == null || info.getDuration() > mapInfo.getDuration()){
map1.put(info.getPosition(),info);
}
}
return map1;
};
}

@Override
public Function<Map<String, PersonPositionDuration>, Map<String, Person>> finisher() {
return mapInfo -> mapInfo
.entrySet()
.stream()
.map(Map.Entry::getValue)
.collect(Collectors.toMap(
PersonPositionDuration::getPosition,
PersonPositionDuration::getPerson));
}

@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
});

result = getCoolestByPositionFromStream(employees.stream().flatMap(CollectorsExercise1::employeeInfo));
return result;
}

private static Stream<PersonPositionDuration> employeeInfo(Employee employee) {
return employee.getJobHistory().stream()
.map(entry -> new PersonPositionDuration(employee.getPerson(),
entry.getPosition(),
entry.getDuration()));
}

private static Map<String,Person> getCoolestByPositionFromStream(Stream<PersonPositionDuration> upstream){
return upstream
.collect(Collectors.toMap(PersonPositionDuration::getPosition,Function.identity(),
(ppd1,ppd2) -> ppd2.getDuration() > ppd1.getDuration() ? ppd2 : ppd1))
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,entry -> entry.getValue().getPerson()));
}

@Test
Expand All @@ -75,8 +144,19 @@ 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<String, Person> getCoolestByPosition2(List<Employee> employees) {
// TODO
throw new UnsupportedOperationException();
return getCoolestByPositionFromStream(employees.stream()
.flatMap(CollectorsExercise1::employeeInfoDuration));
}

private static Stream<PersonPositionDuration> employeeInfoDuration(Employee employee) {
return employeeInfo(employee)
.collect(Collectors.groupingBy(PersonPositionDuration::getPosition))
.entrySet()
.stream()
.map(entry -> new PersonPositionDuration(
employee.getPerson(),
entry.getKey(),
entry.getValue().stream().mapToInt(PersonPositionDuration::getDuration).sum()));
}

private List<Employee> getEmployees() {
Expand Down
176 changes: 92 additions & 84 deletions src/test/java/part2/exercise/CollectorsExercise2.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
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 {


private static String generateString() {
final String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final int maxLength = 10;
Expand Down Expand Up @@ -131,15 +133,15 @@ public Map<String, List<Key>> getKnownKeys() {
}
}

private static class MapPair {
public static class MapPair {
private final Map<String, Key> keyById;
private final Map<String, List<Value>> valueById;
private final Map<String, Set<Value>> valueById;

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

public MapPair(Map<String, Key> keyById, Map<String, List<Value>> valueById) {
public MapPair(Map<String, Key> keyById, Map<String, Set<Value>> valueById) {
this.keyById = keyById;
this.valueById = valueById;
}
Expand All @@ -148,17 +150,67 @@ public Map<String, Key> getKeyById() {
return keyById;
}

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

private static <K, V, M extends Map<K, V>>
static class MapPairCollector implements Collector<Pair, MapPair, MapPair> {

@Override
public Supplier<MapPair> supplier() {
return MapPair::new;
}

@Override
public BiConsumer<MapPair, Pair> accumulator() {
return (MapPair mapPair, Pair pair) -> {
mapPair.getKeyById().put(pair.getKey().getId(), pair.getKey());
mapPair.getValueById()
.merge(
pair.getValue().getKeyId(),
new HashSet<>(Collections.singletonList(pair.getValue())),
(values, values2) -> {
values.addAll(values2);
return values;
});
};
}

@Override
public BinaryOperator<MapPair> combiner() {
return (mapPair, mapPair2) -> {
BinaryOperator<Map<String, Key>> keyMerger = mapMerger((key, key2) -> key);
Map<String, Key> keyMap = keyMerger.apply(mapPair.getKeyById(), mapPair2.getKeyById());

BinaryOperator<Map<String, Set<Value>>> valueMerger = mapMerger((values, values2) -> {
values.addAll(values2);
return values;
});
Map<String, Set<Value>> valueMap = valueMerger.apply(mapPair.getValueById(), mapPair2.getValueById());

return new MapPair(keyMap, valueMap);
};
}

@Override
public Function<MapPair, MapPair> finisher() {
return Function.identity();
}

@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(
Characteristics.UNORDERED,
Characteristics.IDENTITY_FINISH));
}
}

public static <K, V, M extends Map<K, V>>
BinaryOperator<M> mapMerger(BinaryOperator<V> mergeFunction) {
return (m1, m2) -> {
for (Map.Entry<K, V> e : m2.entrySet()) {
for (Map.Entry<K, V> e : m2.entrySet())
m1.merge(e.getKey(), e.getValue(), mergeFunction);
}
return m1;
};
}
Expand All @@ -168,90 +220,46 @@ public void collectKeyValueMap() {
final List<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(
p -> p.getKey().getId(),
Pair::getKey,
(key, key2) -> key)
);

final Map<String, Set<Value>> valuesMap1 = pairs.stream()
.collect(
groupingBy(
p -> p.getValue().getKeyId(),
mapping(Pair::getValue, toSet())
)
);

// В каждом Map.Entry id ключа должно совпадать с keyId для каждого значения в списке
// final Map<Key, List<Value>> keyValuesMap1 = valueMap1.entrySet().stream()...
final Map<Key, Set<Value>> keyValuesMap1 = valuesMap1.entrySet().stream()
.filter(entry -> keyMap1.containsKey(entry.getKey()))
.collect(
toMap(
entry -> keyMap1.get(entry.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();
}

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

@Override
public BinaryOperator<MapPair> combiner() {
// TODO use mapMerger
throw new UnsupportedOperationException();
}

@Override
public Function<MapPair, MapPair> finisher() {
return Function.identity();
}

@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(
Characteristics.UNORDERED,
Characteristics.IDENTITY_FINISH));
}
});

.collect(new MapPairCollector());
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 SubResult res3 = pairs.stream()
.collect(new Collector<Pair, SubResult, SubResult>() {
@Override
public Supplier<SubResult> supplier() {
// TODO
throw new UnsupportedOperationException();
}

@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();
}

@Override
public BinaryOperator<SubResult> combiner() {
// TODO use mapMerger, then check all valuesWithoutKeys
throw new UnsupportedOperationException();
}

@Override
public Function<SubResult, SubResult> finisher() {
// TODO use mapMerger, then check all valuesWithoutKeys
throw new UnsupportedOperationException();
}

@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(
Characteristics.UNORDERED));
}
});
final Map<String, Set<Value>> valuesMap2 = res2.getValueById();

final Map<Key, List<Value>> keyValuesMap3 = res3.getSubResult();
final Map<Key, Set<Value>> keyValuesMap2 = valuesMap2.entrySet().stream()
.filter(entry -> keyMap2.containsKey(entry.getKey()))
.collect(
toMap(
entry -> keyMap2.get(entry.getKey()),
Map.Entry::getValue)
);

// compare results
assertEquals(keyValuesMap1, keyValuesMap2);
}

}