员工数据处理
员工类定义
class Employee {
private int id;
private String name;
private String department;
private double salary;
private int age;
// 构造函数、getter和setter方法
public Employee(int id, String name, String department, double salary, int age) {
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
this.age = age;
}
// Getter方法
public int getId() { return id; }
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
public int getAge() { return age; }
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "', department='" + department +
"', salary=" + salary + ", age=" + age + "}";
}
}
创建员工列表
List<Employee> employees = Arrays.asList(
new Employee(1, "Alice", "HR", 5000, 25),
new Employee(2, "Bob", "IT", 6000, 30),
new Employee(3, "Charlie", "Finance", 5500, 35),
new Employee(4, "David", "IT", 7000, 40),
new Employee(5, "Eve", "HR", 4500, 22),
new Employee(6, "Frank", "Finance", 6500, 45),
new Employee(7, "Grace", "IT", 7500, 32),
new Employee(8, "Heidi", "HR", 5200, 28)
);
示例1:按部门分组
// 按部门分组
Map<String, List<Employee>> employeesByDepartment = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
// 打印每个部门的员工
employeesByDepartment.forEach((department, empList) -> {
System.out.println("部门: " + department);
empList.forEach(emp -> System.out.println(" " + emp.getName()));
});
// 输出:
// 部门: HR
// Alice
// Eve
// Heidi
// 部门: IT
// Bob
// David
// Grace
// 部门: Finance
// Charlie
// Frank
示例2:计算各部门平均工资
// 计算各部门平均工资
Map<String, Double> averageSalaryByDepartment = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
));
// 打印各部门平均工资
averageSalaryByDepartment.forEach((department, avgSalary) -> {
System.out.println(department + ": " + String.format("%.2f", avgSalary));
});
// 输出:
// HR: 4900.00
// IT: 6833.33
// Finance: 6000.00
示例3:找出每个部门最高薪的员工
// 找出每个部门最高薪的员工
Map<String, Optional<Employee>> highestPaidEmployeeByDepartment = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))
));
// 打印每个部门最高薪的员工
highestPaidEmployeeByDepartment.forEach((department, emp) -> {
System.out.println(department + ": " + emp.map(Employee::getName).orElse("No employees"));
});
// 输出:
// HR: Heidi
// IT: Grace
// Finance: Frank
示例4:统计各部门员工数量
// 统计各部门员工数量
Map<String, Long> employeeCountByDepartment = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()
));
// 打印各部门员工数量
employeeCountByDepartment.forEach((department, count) -> {
System.out.println(department + ": " + count);
});
// 输出:
// HR: 3
// IT: 3
// Finance: 2
示例1:统计单词频率
String text = "Hello world hello java world java programming";
Map<String, Long> wordFrequency = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(
String::toLowerCase,
Collectors.counting()
));
wordFrequency.forEach((word, count) -> {
System.out.println(word + ": " + count);
});
// 输出:
// hello: 2
// world: 2
// java: 2
// programming: 1
示例2:并行流处理
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
numbers.add(i);
}
// 串行流计算平方和
long startTime = System.currentTimeMillis();
long sumSequential = numbers.stream()
.mapToLong(n -> n * n)
.sum();
long endTime = System.currentTimeMillis();
System.out.println("串行流结果: " + sumSequential + ", 耗时: " + (endTime - startTime) + "ms");
// 并行流计算平方和
startTime = System.currentTimeMillis();
long sumParallel = numbers.parallelStream()
.mapToLong(n -> n * n)
.sum();
endTime = System.currentTimeMillis();
System.out.println("并行流结果: " + sumParallel + ", 耗时: " + (endTime - startTime) + "ms");
// 输出:
// 串行流结果: 333833500, 耗时: 2ms
// 并行流结果: 333833500, 耗时: 1ms
示例3:分组并求和
class Order {
private int id;
private String customer;
private double amount;
public Order(int id, String customer, double amount) {
this.id = id;
this.customer = customer;
this.amount = amount;
}
public String getCustomer() { return customer; }
public double getAmount() { return amount; }
}
List<Order> orders = Arrays.asList(
new Order(1, "Alice", 100),
new Order(2, "Bob", 200),
new Order(3, "Alice", 150),
new Order(4, "Charlie", 300),
new Order(5, "Bob", 250)
);
// 计算每个客户的订单总金额
Map<String, Double> totalAmountByCustomer = orders.stream()
.collect(Collectors.groupingBy(
Order::getCustomer,
Collectors.summingDouble(Order::getAmount)
));
totalAmountByCustomer.forEach((customer, total) -> {
System.out.println(customer + ": " + total);
});
// 输出:
// Alice: 250.0
// Bob: 450.0
// Charlie: 300.0
示例4:多级分组
class Product {
private String name;
private String category;
private String subCategory;
private double price;
public Product(String name, String category, String subCategory, double price) {
this.name = name;
this.category = category;
this.subCategory = subCategory;
this.price = price;
}
public String getCategory() { return category; }
public String getSubCategory() { return subCategory; }
public double getPrice() { return price; }
}
List<Product> products = Arrays.asList(
new Product("iPhone", "Electronics", "Phones", 999),
new Product("MacBook", "Electronics", "Computers", 1999),
new Product("iPad", "Electronics", "Tablets", 799),
new Product("T-Shirt", "Clothing", "Men", 29),
new Product("Dress", "Clothing", "Women", 79),
new Product("Jeans", "Clothing", "Men", 59)
);
// 按类别和子类别分组
Map<String, Map<String, List<Product>>> productsByCategory = products.stream()
.collect(Collectors.groupingBy(
Product::getCategory,
Collectors.groupingBy(Product::getSubCategory)
));
// 打印分组结果
productsByCategory.forEach((category, subCategories) -> {
System.out.println("类别: " + category);
subCategories.forEach((subCategory, productList) -> {
System.out.println(" 子类别: " + subCategory);
productList.forEach(product -> System.out.println(" " + product.getPrice()));
});
});
// 输出:
// 类别: Electronics
// 子类别: Phones
// 999.0
// 子类别: Computers
// 1999.0
// 子类别: Tablets
// 799.0
// 类别: Clothing
// 子类别: Men
// 29.0
// 59.0
// 子类别: Women
// 子类别: Women
// 79.0