Java from entry to master chapter exercises - Chapter Fourteen

Java from entry to master chapter exercises - Chapter Fourteen

Exercise 1 Calculate factorial

Comprehensive exercise 1: Calculate the factorial Create an anonymous method through the Function interface, which can return the factorial result of an integer.

package org.hj.chapter14;

import java.util.function.Function;

public class CalculateFactorial {
    
    

    public static void main(String[] args) {
    
    
        int n = 3;

        Function<Integer, Integer> factorial = x -> {
    
    
            int result = 1;
            for (int i = 2; i <= x; i++) {
    
    
                result *= i;
            }
            return result;
        };

        int result = factorial.apply(n);
        System.out.println(n + "! = " + result);
    }
}

Exercise 2 Find employees who are older than the average age

Comprehensive exercise 2: find employees who are older than the average age Combining the content of Section 14.3, find employees who are older than the average age.
Use the List collection to store employee information, and stream API to filter and output employees whose age is older than the average age.

package org.hj.chapter14;

import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
import java.util.stream.Collectors;

public class FindEmployee {
    
    

    public static void main(String[] args) {
    
    
        // 定义员工列表
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Alice", 25));
        employees.add(new Employee("Bob", 30));
        employees.add(new Employee("Charlie", 27));
        employees.add(new Employee("David", 35));
        employees.add(new Employee("Emma", 29));

        // 计算所有员工的平均年龄
        OptionalDouble averageAge = employees.stream()
                .mapToInt(Employee::getAge)
                .average();

        // 筛选出年龄大于平均年龄的员工
        List<Employee> olderEmployees = employees.stream()
                .filter(e -> e.getAge() > averageAge.getAsDouble())
                .collect(Collectors.toList());

        // 输出结果
        System.out.println("平均年龄: " + averageAge.orElse(0));
        System.out.println("找到员工: " + olderEmployees);
    }

}

class Employee {
    
    

    private String name;
    private int age;

    public Employee(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }

    @Override
    public String toString() {
    
    
        return name + " (" + age + ")";
    }

}

Guess you like

Origin blog.csdn.net/dedede001/article/details/130411447