/
akupan2012
/
javacoreStream2.4
Обзор
Документация
Войти
/
akupan2012
/
javacoreStream2.4
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Main.java
148 строк
6 KB
akupan2012
upload files
25 фев 2026, 21:06
Верифицирован
25 фев 2026, 21:06
b16e9e2
Код
Авторство
О чём код?
import java.util.*; import java.util.stream.Collectors; enum Sex { MAN, WOMAN } enum Education { HIGHER, SECONDARY, PRIMARY } class Person { private final String name; private final String family; private final int age; private final Sex sex; private final Education education; public Person(String name, String family, int age, Sex sex, Education education) { this.name = name; this.family = family; this.age = age; this.sex = sex; this.education = education; } public String getName() { return name; } public String getFamily() { return family; } public int getAge() { return age; } public Sex getSex() { return sex; } public Education getEducation() { return education; } @Override public String toString() { return String.format("%s %s (%d лет, %s, %s)", name, family, age, sex, education); } } public class Main { public static void main(String[] args) { try { // Замер времени начала long startTime = System.currentTimeMillis(); // Генерация данных System.out.println("Генерация данных..."); List<String> names = Arrays.asList("Jack", "Connor", "Harry", "George", "Samuel", "John"); List<String> families = Arrays.asList("Evans", "Young", "Harris", "Wilson", "Davies", "Adamson", "Brown"); Collection<Person> persons = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 10_000_000; i++) { persons.add(new Person( names.get(random.nextInt(names.size())), families.get(random.nextInt(families.size())), random.nextInt(100), Sex.values()[random.nextInt(Sex.values().length)], Education.values()[random.nextInt(Education.values().length)]) ); } System.out.println("Данные сгенерированы. Всего записей: " + persons.size()); System.out.println("----------------------------------------"); // Задание 1: Найти количество несовершеннолетних (младше 18 лет) long minorsCount = persons.parallelStream() .filter(person -> person.getAge() < 18) .count(); System.out.println("Количество несовершеннолетних: " + minorsCount); // Задание 2: Получить список фамилий призывников (мужчины от 18 до 27 лет) List<String> conscripts = persons.parallelStream() .filter(person -> person.getSex() == Sex.MAN) .filter(person -> person.getAge() >= 18 && person.getAge() <= 27) .map(Person::getFamily) .collect(Collectors.toList()); System.out.println("Количество призывников: " + conscripts.size()); // Вывод первых 10 фамилий призывников System.out.println("Первые 10 фамилий призывников: " + conscripts.stream().limit(10).collect(Collectors.toList())); // Задание 3: Получить отсортированный по фамилии список потенциально работоспособных людей // с высшим образованием (женщины 18-60 лет, мужчины 18-65 лет) List<Person> employable = persons.parallelStream() .filter(person -> person.getEducation() == Education.HIGHER && person.getAge() >= 18 && ((person.getSex() == Sex.WOMAN && person.getAge() <= 60) || (person.getSex() == Sex.MAN && person.getAge() <= 65))) .sorted(Comparator.comparing(Person::getFamily)) .collect(Collectors.toList()); System.out.println("Количество работоспособных с высшим образованием: " + employable.size()); // Вывод первых 10 работоспособных System.out.println("Первые 10 работоспособных (по фамилии):"); employable.stream() .limit(10) .forEach(System.out::println); System.out.println("----------------------------------------"); // Дополнительная статистика System.out.println("Дополнительная статистика:"); // Средний возраст по полу Map<Sex, Double> averageAgeBySex = persons.parallelStream() .collect(Collectors.groupingBy( Person::getSex, Collectors.averagingInt(Person::getAge) )); System.out.println("Средний возраст: мужчины - " + String.format("%.2f", averageAgeBySex.get(Sex.MAN)) + ", женщины - " + String.format("%.2f", averageAgeBySex.get(Sex.WOMAN))); // Распределение по образованию Map<Education, Long> countByEducation = persons.parallelStream() .collect(Collectors.groupingBy( Person::getEducation, Collectors.counting() )); System.out.println("Распределение по образованию: " + countByEducation); // Замер времени окончания long endTime = System.currentTimeMillis(); System.out.println("----------------------------------------"); System.out.println("Время выполнения: " + (endTime - startTime) + " мс"); } catch (Exception e) { System.err.println("Ошибка при обработке данных: " + e.getMessage()); e.printStackTrace(); } } }