Skip to content

Lesson 57 (stream collect collector)#103

Open
Binary-Cat-01 wants to merge 1 commit intoKFalcon2022:for-prfrom
Binary-Cat-01:lesson_57_collect_collector
Open

Lesson 57 (stream collect collector)#103
Binary-Cat-01 wants to merge 1 commit intoKFalcon2022:for-prfrom
Binary-Cat-01:lesson_57_collect_collector

Conversation

@Binary-Cat-01
Copy link
Copy Markdown

No description provided.

public List<Employee> calculate(List<Department> departments) {
return null;
return departments.stream()
.flatMap(d -> d.getEmployees()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Вложенные цепочки вызовов обычно усложняют читаемость кода. Вполне можно заменить на map+flatMap

return departments.stream()
.flatMap(d -> d.getEmployees()
.stream())
.distinct()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

зачем?

return null;
return departments.stream()
.flatMap(d -> d.getEmployees()
.stream())
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

то же, что и выше, дальше подобное не буду дублировать

return departments.stream()
.flatMap(d -> d.getEmployees()
.stream())
.distinct()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

То же, что и выше

return departments.stream()
.collect(Collectors.groupingBy(Department::getName, Collectors.flatMapping(
d -> d.getEmployees()
.stream(), Collectors.averagingDouble(Employee::getAge))));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

я очень большой сторонник правила точка-строчка, но когда стрим или другая цепочка - не единственный параметр метода, смотрится такая конструкция мутно

.collect(Collectors.groupingBy(Department::getName, Collectors.teeing(Collectors.flatMapping(
d -> d.getEmployees()
.stream()
.filter(e -> !e.isMale()), Collectors.counting()), Collectors.flatMapping(
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Collectors.flatMapping( логичнее бы на след строку перенести. Как и предыдущий

d -> d.getEmployees()
.stream(),
Collectors.collectingAndThen(Collectors.summarizingInt(Employee::getAge),
s -> s.getMax() - s.getMin()))));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

считаем лишние параметры, в остальном - элегантное решение

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Пожалуй, лучшее, чем предложено в разборе

return departments.stream()
.flatMap(d -> d.getEmployees()
.stream())
.filter(e -> !e.isMale())
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Как насчет Predicate.not()?

.flatMap(d -> d.getEmployees()
.stream())
.filter(e -> !e.isMale())
.distinct()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

зачем?)

.stream())
.filter(e -> !e.isMale())
.distinct()
.collect(Collectors.collectingAndThen(Collectors.toList(), women -> women.size() > 30 ?
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Я в таких случаях обычно предпочитаю Optional и цепочку уже в нем отстраивать. Чуть легче разбирать

.flatMap(d -> d.getEmployees()
.stream())
.distinct()
.collect(Collectors.teeing(Collectors.filtering(Employee::isMale, Collectors.toList()),
Copy link
Copy Markdown
Owner

@KFalcon2022 KFalcon2022 Oct 2, 2024

Choose a reason for hiding this comment

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

teeing - штука, которую в дальнейшем советую не юзать без крайней необходимости. Бывает слишком сложно разобрать, что к чему, если логика нетривиальная. Что до лишнего списка - он, считай, идет по цене вызова фильтров и создания самого объекта списка. Т.е. там не будет именно х2 прогона каждого элемента, если тебя это беспокоило. Просто к каждому элементу при обработке применится по два набора операций

.flatMap(d -> d.getEmployees()
.stream())
.distinct()
.collect(Collectors.teeing(Collectors.filtering(Employee::isMale, Collectors.counting()),
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

кажется, перенеси ты Collectors.filtering(Employee::isMale, Collectors.counting()), - читать было бы чутка легче

d -> d.getEmployees()
.stream()
.filter(e -> !e.isMale())
.distinct(), Collectors.counting()), (mans, women) -> mans > women)));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Можно лаконичнее

return null;
return departments.stream()
.collect(Collectors.toMap(Department::getName,
d -> (double) d.getVacancyAmount() * 100 / d.getEmployees()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

домножение на 100 - удел отвечающих за отображение данных:) шутка, но в каждой шутке...

return departments.stream()
.collect(Collectors.toMap(Department::getName,
d -> (double) d.getVacancyAmount() * 100 / d.getEmployees()
.size()));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

лишний перенос. Цель понятна, но читаемость портит

@Override
public Integer calculate(List<Department> departments) {
return null;
return departments.stream().mapToInt(Department::getVacancyAmount).sum();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

точка-строчка:)

return null;
return departments.stream()
.map(Department::getName)
.collect(Collectors.joining(", ", "", "."));
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Про точку речи не было)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants