Skip to content

Aleksandra Pankratova #62

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 3 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(10)
.collect(toList());
}
}
46 changes: 37 additions & 9 deletions src/test/java/part1/exercise/StreamsExercise1.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;

public class StreamsExercise1 {
// https://youtu.be/kxgo7Y4cdA8 Сергей Куксенко и Алексей Шипилёв — Через тернии к лямбдам, часть 1
Expand All @@ -25,14 +26,40 @@ public class StreamsExercise1 {

@Test
public void getAllEpamEmployees() {
List<Person> epamEmployees = null;// TODO all persons with experience in epam
throw new UnsupportedOperationException();
List<Employee> epamList = generateEmployeeList();// all persons with experience in epam
List<Person> epamEmployees = epamList.stream()
.filter(e -> e.getJobHistory()
.stream()
.map(JobHistoryEntry::getEmployer)
.anyMatch(emp -> emp.equalsIgnoreCase("epam")))
.map(Employee::getPerson)
.collect(toList());
List<Person> expectedList = new ArrayList<>();
epamList.forEach(e -> {
for (JobHistoryEntry job : e.getJobHistory()) {
if (job.getEmployer().equals("epam")) {
expectedList.add(e.getPerson());
break;
}
}
});
assertEquals(epamEmployees, expectedList);
}

@Test
public void getEmployeesStartedFromEpam() {
List<Person> epamEmployees = null;// TODO all persons with first experience in epam
throw new UnsupportedOperationException();
List<Employee> emp = generateEmployeeList();// all persons with first experience in epam
List<Person> epamEmployees = emp.stream()
.filter(e -> e.getJobHistory().get(0).getEmployer().equalsIgnoreCase("epam"))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use get - it fails on empty collections.

.map(Employee::getPerson)
.collect(toList());
List<Person> expectedList = new ArrayList<>();
emp.forEach(e -> {
if (e.getJobHistory().get(0).getEmployer().equalsIgnoreCase("epam")) {
expectedList.add(e.getPerson());
}
});
assertEquals(epamEmployees, expectedList);
}

@Test
Expand All @@ -49,11 +76,12 @@ public void sumEpamDurations() {
}
}

// TODO
throw new UnsupportedOperationException();

// int result = ???
// assertEquals(expected, result);
int result = employees.stream()
.flatMap(e -> e.getJobHistory().stream())
.filter(emp -> emp.getEmployer().equalsIgnoreCase("epam"))
.mapToInt(JobHistoryEntry::getDuration)
.sum();
assertEquals(expected, result);
}

}
109 changes: 99 additions & 10 deletions src/test/java/part1/exercise/StreamsExercise2.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
import data.Person;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static data.Generator.generateEmployeeList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
import static org.junit.Assert.assertEquals;

Expand All @@ -22,23 +21,113 @@ public class StreamsExercise2 {
// https://youtu.be/O8oN4KSZEXE Сергей Куксенко — Stream API, часть 1
// https://youtu.be/i0Jr2l3jrDA Сергей Куксенко — Stream API, часть 2

// TODO class PersonEmployerPair
// class PersonEmployerPair
private static class PersonEmployerPair {
private final Person person;
private final String employer;

public PersonEmployerPair(Person person, String employer) {
this.person = person;
this.employer = employer;
}

public Person getPerson() {
return person;
}

public String getEmployer() {
return employer;
}
}

private static class PersonEmployerDuration {
private final Person person;
private final String employer;
private final int duration;

PersonEmployerDuration(Person person, String employer, int duration) {
this.person = person;
this.employer = employer;
this.duration = duration;
}

Person getPerson() {
return person;
}

String getEmployer() {
return employer;
}

int getDuration() {
return duration;
}
}

private Stream<PersonEmployerPair> employeesToPairs(Employee employee) {
return employee.getJobHistory().stream()
.map(JobHistoryEntry::getEmployer)
.map(e -> new PersonEmployerPair(employee.getPerson(), e));
}


@Test
public void employersStuffLists() {
Map<String, List<Person>> employersStuffLists = null;// TODO
throw new UnsupportedOperationException();
final List<Employee> employees = getEmployees();
Map<String, List<Person>> employersStuffLists = employees.stream()
.flatMap(this::employeesToPairs)
.collect(Collectors.groupingBy(
PersonEmployerPair::getEmployer,
mapping(PersonEmployerPair::getPerson, toList())));

Map<String, List<Person>> expected = new HashMap<>();
employees.forEach(e -> e.getJobHistory()
.forEach(emp -> {
String employer = emp.getEmployer();
expected.computeIfAbsent(employer, i -> new ArrayList<>());
expected.get(employer).add(e.getPerson());
}));
assertEquals(expected, employersStuffLists);
}

private static PersonEmployerPair firstEmployerPersonPair(Employee employee) {
final JobHistoryEntry jobHistoryEntry = employee.getJobHistory().stream()
.findFirst()
.get();

return new PersonEmployerPair(employee.getPerson(), jobHistoryEntry.getEmployer());
}

@Test
public void indexByFirstEmployer() {
Map<String, List<Person>> employeesIndex = null;// TODO
throw new UnsupportedOperationException();
Map<String, List<Person>> employeesIndex = getEmployees().stream()
.flatMap(e -> e.getJobHistory()
.stream()
.map(j -> new PersonEmployerPair(e.getPerson(), j.getEmployer()))
.limit(1))
.collect(groupingBy(
PersonEmployerPair::getEmployer,
mapping(PersonEmployerPair::getPerson, toList()))
);

Map<String, List<Person>> expected = getEmployees().stream()
.map(StreamsExercise2::firstEmployerPersonPair)
.collect(groupingBy(PersonEmployerPair::getEmployer,
mapping(PersonEmployerPair::getPerson, toList())));

assertEquals(expected, employeesIndex);
}

@Test
public void greatestExperiencePerEmployer() {
Map<String, Person> employeesIndex = null;// TODO
Map<String, Person> employeesIndex = getEmployees().stream()
.flatMap(e -> e.getJobHistory().stream()
.map(emp -> new PersonEmployerDuration(e.getPerson(), emp.getEmployer(), emp.getDuration())))
.collect(groupingBy(
PersonEmployerDuration::getEmployer,
collectingAndThen(
maxBy(comparing(PersonEmployerDuration::getDuration)), p -> p.get().getPerson()))
);

assertEquals(new Person("John", "White", 28), employeesIndex.get("epam"));
}
Expand Down
75 changes: 61 additions & 14 deletions src/test/java/part2/exercise/CollectorsExercise1.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@
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> coolestByPosition1 = getCoolestByPosition(getEmployees());

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

private static class PersonPositionDuration {
Expand Down Expand Up @@ -53,30 +56,75 @@ public int getDuration() {

// With the longest duration on single job
private Map<String, Person> getCoolestByPosition(List<Employee> employees) {
// First option
// Collectors.maxBy
// Collectors.collectingAndThen
// Collectors.groupingBy

// Second option
// Collectors.toMap
// iterate twice: stream...collect(...).stream()...
// TODO
throw new UnsupportedOperationException();
return getPersonPositionDurationStream(employees).collect(
groupingBy(PersonPositionDuration::getPosition,
collectingAndThen(maxBy(Comparator.comparing(PersonPositionDuration::getDuration)),
personPositionDuration -> personPositionDuration.get().getPerson())));
}

private Stream<PersonPositionDuration> getPersonPositionDurationStream(List<Employee> employees) {
return employees
.stream()
.flatMap(e -> e.getJobHistory().stream()
.map(j -> new PersonPositionDuration(e.getPerson(), j.getPosition(), j.getDuration())));
}

@Test
public void getTheCoolestOne2() {
final Map<String, Person> coolestByPosition = getCoolestByPosition2(getEmployees());
final Map<String, Person> coolestByPosition1 = getCoolestByPosition2(getEmployees());

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

// 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 getPersonPositionDurationStream(employees).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, ppd) -> {
map.putIfAbsent(ppd.getPosition(), ppd);
PersonPositionDuration currentPpd = map.get(ppd.getPosition());
if (ppd.getDuration() > currentPpd.getDuration()) {
map.put(ppd.getPosition(), ppd);
}
};
}

@Override
public BinaryOperator<Map<String, PersonPositionDuration>> combiner() {
return (m1, m2) -> {
m2.forEach((k, v) -> m1.merge(k, v, (v1, v2) -> v1.getDuration() > v2.getDuration() ? v1 : v2));
return m1;
};
}

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

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

private List<Employee> getEmployees() {
Expand Down Expand Up @@ -155,5 +203,4 @@ private List<Employee> getEmployees() {
))
);
}

}
Loading