Java

Обработка коллекций через Stream API

Algonexys · 07.08.2026 · 👁 0

Фильтрация, группировка и агрегация вместо циклов — идиоматичная Java 8+.

Код

import java.util.*;
import java.util.stream.*;

record Employee(String name, String department, int salary, int age) {}

public class StreamExamples {
    public static void main(String[] args) {
        List<Employee> staff = List.of(
            new Employee("Иван", "Разработка", 250_000, 32),
            new Employee("Анна", "Разработка", 300_000, 28),
            new Employee("Пётр", "Тестирование", 180_000, 41),
            new Employee("Мария", "Аналитика", 220_000, 35)
        );

        // Группировка по отделу
        Map<String, List<String>> byDept = staff.stream()
            .collect(Collectors.groupingBy(
                Employee::department,
                Collectors.mapping(Employee::name, Collectors.toList())));

        // Средняя зарплата по отделам
        Map<String, Double> avgSalary = staff.stream()
            .collect(Collectors.groupingBy(
                Employee::department,
                Collectors.averagingInt(Employee::salary)));

        // Фильтр + сортировка + сбор в строку
        String senior = staff.stream()
            .filter(e -> e.salary() > 200_000)
            .sorted(Comparator.comparingInt(Employee::salary).reversed()
                              .thenComparing(Employee::name))
            .map(Employee::name)
            .collect(Collectors.joining(", ", "[", "]"));

        // Статистика одним проходом
        IntSummaryStatistics stats = staff.stream()
            .mapToInt(Employee::salary).summaryStatistics();
        System.out.printf("Мин %d, макс %d, среднее %.0f%n",
            stats.getMin(), stats.getMax(), stats.getAverage());

        // Максимум с Optional
        staff.stream().max(Comparator.comparingInt(Employee::age))
             .ifPresent(e -> System.out.println("Старший: " + e.name()));
    }
}