Skip to content

Conversation

@Binary-Cat-01
Copy link

No description provided.

public List<Employee> calculate(List<Department> departments) {
return null;
return departments.stream()
.flatMap(d -> d.getEmployees()
Copy link
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
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
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
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
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
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
Owner

Choose a reason for hiding this comment

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

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

Copy link
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
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
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
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
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
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
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
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
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
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
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