创建一个Employee JAVABean对象
package ght04_Stream;
import java.util.ArrayList;
import java.util.List;public class Employee { // 员工类private String name; // 姓名private int age; // 年龄private double salary; // 工资private String sex; // 性别private String dept; // 部门// 构造方法public Employee(String name, int age, double salary, String sex, String dept) {this.name = name;this.age = age;this.salary = salary;this.sex = sex;this.dept = dept;}// 重写此方法,方便打印输出员工信息public String toString() {return "name=" + name + ", age=" + age + ", salary=" + salary + ", sex=" + sex + ", dept=" + dept;}// 以下是员工属性的getter方法public String getName() {return name;}public int getAge() {return age;}public double getSalary() {return salary;}public String getSex() {return sex;}public String getDept() {return dept;}static List<Employee> getEmpList() { // 提供数据初始化方法List<Employee> list = new ArrayList<Employee>();// 添加员工数据list.add(new Employee("老张", 40, 9000, "男", "运营部"));list.add(new Employee("小刘", 24, 5000, "女", "开发部"));list.add(new Employee("大刚", 32, 7500, "男", "销售部"));list.add(new Employee("翠花", 28, 5500, "女", "销售部"));list.add(new Employee("小马", 21, 3000, "男", "开发部"));list.add(new Employee("老王", 35, 6000, "女", "人事部"));list.add(new Employee("小王", 21, 3000, "女", "人事部"));return list;}
}
利用JAVA流处理Stream测试数据
package ght04_Stream;import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;public class test {public static void main(String[] args) {List<Employee> list = Employee.getEmpList(); //get test data from public classStream<Employee> stream = list.stream(); //get stream object// 分组规则方法,按照员工进行分级(sex)Function<Employee, String> f = Employee::getSex;// 按照部门分成若干List集合,集合中保存员工对象,返回成MapMap<String, List<Employee>> map = stream.collect(Collectors.groupingBy(f));Set<String> keySet = map.keySet(); // 获取Map的 all sexint age = 0; //年龄总和double avg_age = 0.0;for ( Employee e : list ){age += e.getAge();}avg_age = age/list.size();int num = 0;int salary = 5000;int s_num = 0;int a_num = 0;List<Employee>employees = new ArrayList<>();for (String sex : keySet) { // 遍历部门名称集合// find sexif(sex == "男"){List<Employee> deptList = map.get(sex); // 获取sex == "男"System.out.println("男员工人数为: "+deptList.size());for(Employee e : deptList){if(e.getAge() > avg_age){employees.add(e);}}}else{List<Employee> deptList = map.get(sex); // 获取sex == " 女"for(Employee d : deptList){if(d.getSalary() > 5000){s_num++;}if( d.getAge() > avg_age){employees.add(d);}}System.out.println("薪资大于5000的女员工人数为: "+s_num);}}System.out.println("大于平均年龄的员工: ");for (Employee emp : employees) { // 遍历员工集合System.out.println("\t" + emp); // 输出员工信息}}
}