Skip to content
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

Homework.lambda.part3.exercise2 (Mikhaylov) #380

Open
wants to merge 3 commits into
base: mikhaylov
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
49 changes: 49 additions & 0 deletions src/main/java/lambda/data/Employee.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package lambda.data;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Employee {

private final Person person;
private final List<JobHistoryEntry> jobHistory;

public Employee(Person person, List<JobHistoryEntry> jobHistory) {
this.person = person;
this.jobHistory = new ArrayList<>(jobHistory);
}

public Person getPerson() {
return person;
}

public List<JobHistoryEntry> getJobHistory() {
return new ArrayList<>(jobHistory);
}

@Override
public String toString() {
return "Employee@" + hashCode() + " {"
+ "person=" + person + ", "
+ "jobHistory=" + jobHistory + "}";
}

@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
Employee employee = (Employee) object;
return Objects.equals(person, employee.person)
&& Objects.equals(jobHistory, employee.jobHistory);
}

@Override
public int hashCode() {
return Objects.hash(person, jobHistory);
}
}
55 changes: 55 additions & 0 deletions src/main/java/lambda/data/JobHistoryEntry.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package lambda.data;

import java.util.Objects;

public class JobHistoryEntry {

private final String employer;
private final String position;
private final int duration;

public JobHistoryEntry(int duration, String position, String employer) {
this.duration = duration;
this.position = position;
this.employer = employer;
}

public int getDuration() {
return duration;
}

public String getPosition() {
return position;
}

public String getEmployer() {
return employer;
}

@Override
public String toString() {
return "JobHistoryEntry@" + hashCode() + ": {"
+ "duration=" + duration + ", "
+ "position='" + position + "\', "
+ "employer='" + employer + "\'}";
}

@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
JobHistoryEntry entry = (JobHistoryEntry) other;
return duration == entry.duration
&& Objects.equals(position, entry.position)
&& Objects.equals(employer, entry.employer);
}

@Override
public int hashCode() {
return Objects.hash(duration, position, employer);
}
}
64 changes: 64 additions & 0 deletions src/main/java/lambda/data/Person.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package lambda.data;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.Objects;

public class Person implements Serializable {

private final String firstName;
private final String lastName;
private final int age;

public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

public Person() {
firstName = "default";
lastName = "default";
age = -1;
}

public String getFirstName(Person this) {
return firstName;
}

public String getLastName(Person this) {
return this.lastName;
}

public int getAge() {
return age;
}

public String getFullName() {
return firstName + " " + lastName;
}

@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Person person = (Person) other;
return age == person.age
&& Objects.equals(firstName, person.firstName)
&& Objects.equals(lastName, person.lastName);
}

@Override
public int hashCode() {
return Objects.hash(age, firstName, lastName);
}

@Override
public String toString() {
return "Person@" + hashCode() + ": {"
+ "firstName='" + firstName + "', "
+ "lastName='" + lastName + "', "
+ "age=" + age + "}";
}
}
143 changes: 143 additions & 0 deletions src/test/java/lambda/part3/exercise/Exercise2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package lambda.part3.exercise;

import com.google.common.primitives.Chars;
import lambda.data.Employee;
import lambda.data.JobHistoryEntry;
import lambda.data.Person;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;

@SuppressWarnings({"unused", "ConstantConditions"})
class Exercise2 {

private static class MapHelper<T> {

private final List<T> source;

private MapHelper(List<T> source) {
this.source = source;
}

public static <T> MapHelper<T> from(List<T> source) {
return new MapHelper<>(source);
}

public List<T> getMapped() {
return new ArrayList<>(source);
}

/**
* Создает объект для маппинга, передавая ему новый список, построенный на основе исходного.
* Для добавления в новый список каждый элемент преобразовывается с использованием заданной функции.
* ([T], (T -> R)) -> [R]
* @param mapping Функция преобразования элементов.
*/
public <R> MapHelper<R> map(Function<T, R> mapping) {
List<R> list = new ArrayList<>();
this.source.forEach(el -> list.add(mapping.apply(el)));
return from(list);
}

/**
* Создает объект для маппинга, передавая ему новый список, построенный на основе исходного.
* Для добавления в новый список каждый элемент преобразовывается в список с использованием заданной функции.
* ([T], (T -> [R])) -> [R]
* @param flatMapping Функция преобразования элементов.
*/
public <R> MapHelper<R> flatMap(Function<T, List<R>> flatMapping) {
List<R> list = new ArrayList<>();
this.source.forEach(el -> list.addAll(flatMapping.apply(el)));
return from(list);
}
}

@Test
void mapEmployeesToLengthOfTheirFullNamesUsingMapHelper() {
List<Employee> employees = getEmployees();

List<Integer> lengths = MapHelper.from(employees)
.map(Employee::getPerson)
.map(Person::getFullName)
.map(String::length)
.getMapped();

assertThat(lengths, contains(14, 19, 14, 15, 14, 16));
}

@Test
void mapEmployeesToCodesOfLetterTheirPositionsUsingMapHelper() {
List<Employee> employees = getEmployees();

Character [] arr = {'c','a','q'};
final List<Character> characters = Arrays.asList(arr);
List<Integer> codes = MapHelper.from(employees)
.flatMap(Employee::getJobHistory)
.map(JobHistoryEntry::getPosition)
.flatMap(position -> Chars.asList(position.toCharArray()))
.map(ch -> (int) ch)
.getMapped();

assertThat(codes, contains(calcCodes("dev", "dev", "tester", "dev", "dev", "QA", "QA", "dev", "tester", "tester", "QA", "QA", "QA", "dev").toArray()));
}

private static List<Integer> calcCodes(String...strings) {
List<Integer> codes = new ArrayList<>();
for (String string : strings) {
for (char letter : string.toCharArray()) {
codes.add((int) letter);
}
}
return codes;
}

private static List<Employee> getEmployees() {
return Arrays.asList(
new Employee(
new Person("Иван", "Мельников", 30),
Arrays.asList(
new JobHistoryEntry(2, "dev", "EPAM"),
new JobHistoryEntry(1, "dev", "google")
)),
new Employee(
new Person("Александр", "Дементьев", 28),
Arrays.asList(
new JobHistoryEntry(1, "tester", "EPAM"),
new JobHistoryEntry(1, "dev", "EPAM"),
new JobHistoryEntry(1, "dev", "google")
)),
new Employee(
new Person("Дмитрий", "Осинов", 40),
Arrays.asList(
new JobHistoryEntry(3, "QA", "yandex"),
new JobHistoryEntry(1, "QA", "mail.ru"),
new JobHistoryEntry(1, "dev", "mail.ru")
)),
new Employee(
new Person("Анна", "Светличная", 21),
Collections.singletonList(
new JobHistoryEntry(1, "tester", "T-Systems")
)),
new Employee(
new Person("Игорь", "Толмачёв", 50),
Arrays.asList(
new JobHistoryEntry(5, "tester", "EPAM"),
new JobHistoryEntry(6, "QA", "EPAM")
)),
new Employee(
new Person("Иван", "Александров", 33),
Arrays.asList(
new JobHistoryEntry(2, "QA", "T-Systems"),
new JobHistoryEntry(3, "QA", "EPAM"),
new JobHistoryEntry(1, "dev", "EPAM")
))
);
}
}