Skip to content

Golubev Nikita - Part3 #85

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());
}
}
92 changes: 81 additions & 11 deletions src/test/java/part3/exercise/CollectorCombination.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
import part2.exercise.CollectorsExercise2.Key;
import part2.exercise.CollectorsExercise2.Value;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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 static java.util.stream.Collectors.*;
import static org.junit.Assert.assertEquals;

public class CollectorCombination {

Expand All @@ -30,12 +36,66 @@ public A getA() {
public B getB() {
return b;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Pair<?, ?> pair = (Pair<?, ?>) o;

if (!a.equals(pair.a)) return false;
return b.equals(pair.b);
}

@Override
public int hashCode() {
int result = a.hashCode();
result = 31 * result + b.hashCode();
return result;
}
}

private static <T, M1, M2, R1, R2> Collector<T, Pair<M1, M2>, Pair<R1, R2>> paired(Collector<T, M1, R1> c1,
Collector<T, M2, R2> c2) {
// TODO
throw new UnsupportedOperationException();
return new Collector<T, Pair<M1, M2>, Pair<R1, R2>>() {
@Override
public Supplier<Pair<M1, M2>> supplier() {
return () -> new Pair<>(
c1.supplier().get(),
c2.supplier().get()
);
}

@Override
public BiConsumer<Pair<M1, M2>, T> accumulator() {
return (m1M2Pair, t) -> {
c1.accumulator().accept(m1M2Pair.getA(), t);
c2.accumulator().accept(m1M2Pair.getB(), t);
};
}

@Override
public BinaryOperator<Pair<M1, M2>> combiner() {
return (m1M2Pair1, m1M2Pair2) -> new Pair<>(
c1.combiner().apply(m1M2Pair1.getA(), m1M2Pair2.getA()),
c2.combiner().apply(m1M2Pair1.getB(), m1M2Pair2.getB())
);
}

@Override
public Function<Pair<M1, M2>, Pair<R1, R2>> finisher() {
return m1M2Pair -> new Pair<>(
c1.finisher().apply(m1M2Pair.getA()),
c2.finisher().apply(m1M2Pair.getB())
);
}

@Override
public Set<Characteristics> characteristics() {
return new HashSet<>();
}
};
}

@Test
Expand All @@ -48,17 +108,27 @@ public void collectKeyValueMap() {
// Перепишите решение в слещующем виде:
final List<CollectorsExercise2.Pair> pairs = CollectorsExercise2.generatePairs(10, 100);

final Pair<Map<String, Key>, Map<String, List<Value>>> res2 = pairs.stream()
.collect(
paired(
mapping(CollectorsExercise2.Pair::getKey, toMap(Key::getId, Function.identity(), (x, y) -> x)),
mapping(CollectorsExercise2.Pair::getValue, groupingBy(Value::getKeyId))
)
);
final Pair<Map<String, Key>, Map<String, List<Value>>> res1;

Map<String, Key> collect = pairs.stream().collect(mapping(CollectorsExercise2.Pair::getKey, toMap(Key::getId,
Function.identity(),
(x, y) -> x))
);

Map<String, List<Value>> collect1 = pairs.stream().collect(mapping(CollectorsExercise2.Pair::getValue,
groupingBy(Value::getKeyId)));

res1 = new Pair<>(collect, collect1);

final Pair<Map<String, Key>, Map<String, List<Value>>> res2 = pairs.stream()
.collect(paired(mapping(CollectorsExercise2.Pair::getKey,
toMap(Key::getId,
Function.identity(),
(x, y) -> x)),
mapping(CollectorsExercise2.Pair::getValue,
groupingBy(Value::getKeyId))));

// TODO tests
throw new UnsupportedOperationException();
assertEquals(res1, res2);
}

}
43 changes: 23 additions & 20 deletions src/test/java/part3/exercise/lambda/LambdaExercise.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,27 @@ public class LambdaExercise {
public void supply() {
final Person person = new Person("John", "Galt", 30);

final Supplier<Person> getPerson = null; // TODO return person from Supplier
final Supplier<Person> getPerson = () -> person;

assertEquals(person, getPerson.get());
}

@Test
public void function() {
final Function<Person, String> getPersonName1 = null; // TODO get the name of person using expression lambda
final Person person = new Person("John", "Galt", 30);

final Function<Person, String> getPersonName2 = null; // TODO get the name of person using method reference
final Function<Person, String> getPersonName1 =
p -> person.getFirstName();

// TODO get the name of person and log it to System.out using statement lambda: {}
final Function<Person, String> getPersonNameAndLogIt = null;
final Function<Person, String> getPersonName2 =
Person::getFirstName;

final Function<Person, String> getPersonNameAndLogIt = p -> {
final String firstName = p.getFirstName();
System.out.println(firstName);
return firstName;
};

final Person person = new Person("John", "Galt", 30);

assertEquals(person.getFirstName(), getPersonName1.apply(person));
assertEquals(person.getFirstName(), getPersonName2.apply(person));
Expand All @@ -38,21 +44,20 @@ public void function() {

@Test
public void combineFunctions() {
final Function<Person, String> getPersonName = null; // TODO get the name of person
final Person person = new Person("John", "Galt", 30);

final Function<Person, String> getPersonName = Person::getFirstName;

assertEquals("John", getPersonName.apply(new Person("John", "Galt", 30)));

final Function<String, Integer> getStringLength = null; // TODO get string length
final Function<String, Integer> getStringLength = String::length;

assertEquals(Integer.valueOf(3), getStringLength.apply("ABC"));

// TODO get person name length using getPersonName and getStringLength without andThen
final Function<Person, Integer> getPersonNameLength1 = null;
final Function<Person, Integer> getPersonNameLength1 = p -> getStringLength.apply(getPersonName.apply(p));

// TODO get person name length using getPersonName and getStringLength with andThen
final Function<Person, Integer> getPersonNameLength2 = null;
final Function<Person, Integer> getPersonNameLength2 = getPersonName.andThen(getStringLength);

final Person person = new Person("John", "Galt", 30);

assertEquals(Integer.valueOf(4), getPersonNameLength1.apply(person));
assertEquals(Integer.valueOf(4), getPersonNameLength2.apply(person));
Expand All @@ -68,26 +73,24 @@ private Person createPerson(PersonFactory pf) {

// ((T -> R), (R -> boolean)) -> (T -> boolean)
private <T, R> Predicate<T> combine(Function<T, R> f, Predicate<R> p) {
// TODO
throw new UnsupportedOperationException();
return t -> p.test(f.apply(t));
}

@Test
public void methodReference() {
// TODO use only method reverences here.
final Person person = createPerson(null); // TODO
final Person person = createPerson(Person::new);

assertEquals(new Person("John", "Galt", 66), person);

final Function<Person, String> getPersonName = null; // TODO
final Function<Person, String> getPersonName = Person::getFirstName;

assertEquals("John", getPersonName.apply(person));

final Predicate<String> isJohnString = null; // TODO using method reference check that "John" equals string parameter
final Predicate<String> isJohnString = "John"::equals;

final Predicate<Person> isJohnPerson = combine(getPersonName, isJohnString);

assertEquals(true, isJohnPerson.test(person));
}

}
}
69 changes: 54 additions & 15 deletions src/test/java/part3/exercise/stream/StreamsExercise.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,15 @@

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.*;
import static org.junit.Assert.assertEquals;

public class StreamsExercise {
Expand All @@ -19,7 +25,8 @@ public class StreamsExercise {
public void getAllJobHistoryEntries() {
final List<Employee> employees = getEmployees();

final List<JobHistoryEntry> jobHistoryEntries = null; // TODO
final List<JobHistoryEntry> jobHistoryEntries =
employees.stream().flatMap(j -> j.getJobHistory().stream()).collect(toList());

assertEquals(22, jobHistoryEntries.size());
}
Expand All @@ -29,7 +36,10 @@ public void getSumDuration() {
// sum all durations for all persons
final List<Employee> employees = getEmployees();

final int sumDurations = 0; // TODO
final int sumDurations = employees.stream()
.flatMap(j -> j.getJobHistory().stream())
.mapToInt(JobHistoryEntry::getDuration)
.sum();

assertEquals(72, sumDurations);
}
Expand Down Expand Up @@ -64,7 +74,10 @@ public String toString() {
public void indexPersonsByEmployer1() {
final List<Employee> employees = getEmployees();

final Map<String, List<PersonEmployer>> index = null; // TODO
final Map<String, List<PersonEmployer>> index = employees.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonEmployer(e.getPerson(), j.getEmployer())))
.collect(groupingBy(PersonEmployer::getEmployer));

assertEquals(11, index.get("epam").size());
}
Expand All @@ -73,7 +86,9 @@ public void indexPersonsByEmployer1() {
public void indexPersonsByEmployer2() {
final List<Employee> employees = getEmployees();

final Map<String, List<Person>> index = null; // TODO
final Map<String, List<Person>> index = employees.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonEmployer(e.getPerson(), j.getEmployer()))).collect(groupingBy(PersonEmployer::getEmployer, mapping(PersonEmployer::getPerson, toList())));

assertEquals(11, index.get("epam").size());
}
Expand Down Expand Up @@ -106,15 +121,20 @@ public String toString() {

private PersonDuration sumAllPersonDurations(Employee e) {
// TODO
throw new UnsupportedOperationException();
final int totalDuration = e.getJobHistory().stream()
.mapToInt(JobHistoryEntry::getDuration)
.sum();
return new PersonDuration(e.getPerson(), totalDuration);
}

@Test
public void getSumPersonDuration() {
// sum all durations for each person
final List<Employee> employees = getEmployees();

final Map<Person, Integer> personDuration = null; // TODO use sumAllPersonDurations
final Map<Person, Integer> personDuration = employees.stream()
.map(this::sumAllPersonDurations)
.collect(toMap(PersonDuration::getPerson, PersonDuration::getDuration));

assertEquals(Integer.valueOf(8), personDuration.get(new Person("John", "Doe", 24)));
}
Expand All @@ -139,14 +159,19 @@ public Map<String, Integer> getDurationByPositionIndex() {

private static PersonPositionIndex getPersonPositionIndex(Employee e) {
// TODO
throw new UnsupportedOperationException();
final Map<String, Integer> collect = e.getJobHistory().stream()
.collect(groupingBy(JobHistoryEntry::getPosition, summingInt(JobHistoryEntry::getDuration)));
return new PersonPositionIndex(e.getPerson(), collect);
}

@Test
public void getSumDurationsForPersonByPosition() {
final List<Employee> employees = getEmployees();

final List<PersonPositionIndex> personIndexes = null; // TODO use getPersonPositionIndex
final List<PersonPositionIndex> personIndexes =
employees.stream()
.map(StreamsExercise::getPersonPositionIndex)
.collect(toList());

assertEquals(1, personIndexes.get(3).getDurationByPositionIndex().size());
}
Expand Down Expand Up @@ -175,12 +200,20 @@ public int getDuration() {
}
}

private Stream<PersonPositionDuration> getPersonPositionDurationStream(List<Employee> employees) {
return employees.stream()
.map(StreamsExercise::getPersonPositionIndex)
.flatMap(e -> e.getDurationByPositionIndex().entrySet().stream()
.map(p -> new PersonPositionDuration(e.person, p.getKey(), p.getValue()))
);
}

@Test
public void getDurationsForEachPersonByPosition() {
final List<Employee> employees = getEmployees();

final List<PersonPositionDuration> personPositionDurations = null; // TODO

final List<PersonPositionDuration> personPositionDurations =
getPersonPositionDurationStream(employees).collect(toList());

assertEquals(17, personPositionDurations.size());
}
Expand All @@ -190,8 +223,11 @@ public void getCoolestPersonByPosition1() {
// Get person with max duration on given position
final List<Employee> employees = getEmployees();

final Map<String, PersonPositionDuration> coolestPersonByPosition = null;// TODO

final Map<String, PersonPositionDuration> coolestPersonByPosition =
getPersonPositionDurationStream(employees)
.collect(toMap(PersonPositionDuration::getPosition,
Function.identity(),
BinaryOperator.maxBy(Comparator.comparingInt(PersonPositionDuration::getDuration))));

assertEquals(new Person("John", "White", 22), coolestPersonByPosition.get("QA").getPerson());
}
Expand All @@ -201,8 +237,11 @@ public void getCoolestPersonByPosition2() {
// Get person with max duration on given position
final List<Employee> employees = getEmployees();

final Map<String, Person> coolestPersonByPosition = null; // TODO

final Map<String, Person> coolestPersonByPosition =
getPersonPositionDurationStream(employees)
.collect(groupingBy(PersonPositionDuration::getPosition,
collectingAndThen(maxBy(Comparator.comparingInt(PersonPositionDuration::getDuration)),
p -> p.get().getPerson())));

assertEquals(new Person("John", "White", 22), coolestPersonByPosition.get("QA"));
}
Expand Down Expand Up @@ -282,4 +321,4 @@ private List<Employee> getEmployees() {
}


}
}