Java从入门到精通章节练习题——第十四章

Java从入门到精通章节练习题——第十四章

Exercise 1 计算阶乘

综合练习1:计算阶乘 通过Function接口创建一个匿名方法,该方法可以返回整数的阶乘结果。

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 找出大于平均年龄的员工

综合练习2:找出大于平均年龄的员工 结合第14.3节的内容,找出大于平均年龄的员工。
利用List集合存放员工信息,stream API过滤年龄大于平均年龄的员工并输出。

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 + ")";
    }

}

猜你喜欢

转载自blog.csdn.net/dedede001/article/details/130411447
今日推荐