1、创建一个雇员类Employee,定义雇员姓名name属性和雇员工资salary属性,在测试类中创建一个List集合并存储5个雇员对象,然后完成如下两个功能(7分): 计算这5个雇员的平均薪资 输入一个员工姓氏,输出符合该姓氏的所有员工信息 输出工资最高的前三名员工的姓名【使用Stream流】
时间: 2023-04-06 22:00:54 浏览: 326
Employee类的定义:
```
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
```
测试类的代码:
```
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TestEmployee {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("张三", 5000));
employees.add(new Employee("李四", 6000));
employees.add(new Employee("王五", 7000));
employees.add(new Employee("赵六", 8000));
employees.add(new Employee("钱七", 9000));
// 计算平均薪资
double averageSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.average()
.orElse(0);
System.out.println("平均薪资:" + averageSalary);
// 根据姓氏查找员工信息
String surname = "张";
List<Employee> employeesWithSurname = employees.stream()
.filter(e -> e.getName().startsWith(surname))
.collect(Collectors.toList());
System.out.println("姓氏为" + surname + "的员工信息:");
employeesWithSurname.forEach(e -> System.out.println(e.getName() + " " + e.getSalary()));
// 输出工资最高的前三名员工的姓名
List<String> top3Names = employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.limit(3)
.map(Employee::getName)
.collect(Collectors.toList());
System.out.println("工资最高的前三名员工的姓名:" + top3Names);
}
}
```
输出结果:
```
平均薪资:7000.0
姓氏为张的员工信息:
张三 5000.0
工资最高的前三名员工的姓名:[钱七, 赵六, 王五]
```
阅读全文