java employee list_使用Java 8 Lambda表达式对Employee类进行操作

packagecoffee.how.to.program.early.objects.chapter15;/*** 定义若干 Employee 实例并加入数组,

* 把数组转换成 list,

* 根据 Employee的Last Name 和 First Name 定义比较器。

* 使用 lambda 和 stream 对 Employee 类进行操作。*/

importjava.util.Arrays;importjava.util.Comparator;importjava.util.List;importjava.util.function.Function;importjava.util.function.Predicate;public classProcessingEmployees {public static voidmain(String[] args) {//定义Employee类数组

Employee[] employees ={new Employee("Jason", "Red", 5000, "IT"),new Employee("Ashley", "Green", 7600, "IT"),new Employee("Matthew", "Indigo", 3587.5, "Sales"),new Employee("James", "Indigo", 4700.77, "Marketing"),new Employee("Luke", "Indigo", 6200, "IT"),new Employee("Jason", "Blue", 3200, "Sales"),new Employee("Wendy", "Brown", 4236.4, "Marketing") };//转换成list

List list =Arrays.asList(employees);//打印全部的Employee信息

System.out.println("Complete Employee List: ");

list.stream().forEach(System.out::println);

System.out.println("-------------------------------");//定义函数式接口,返回boolean值,指定工资范围在大于等于4000小于等于6000的区间。

Predicate four2SixThousand = e -> (e.getSalary() >= 4000 && e.getSalary() <= 6000);//使用 stream 过滤,排序,再循环遍历打印。

list.stream().filter(four2SixThousand).sorted(Comparator.comparing(Employee::getSalary))

.forEach(System.out::println);//打印比较器区间工资最小的Employee信息

System.out.printf("%nFirst employee who earns $4000-$6000:%n%s%n",

list.stream().filter(four2SixThousand).min(Comparator.comparing(Employee::getSalary)).get());

Function byFirstName =Employee::getFirstName;

Function byLastName =Employee::getLastName;//指定比较器比较规则

Comparator lastThenFistComp =Comparator.comparing(byLastName).thenComparing(byFirstName);//先根据last name 比较,如果相同,再比较 first name。

System.out.printf("%nEmployees in ascending order by last name then fist name: %n");

list.stream().sorted(lastThenFistComp).forEach(System.out::println);//先根据first name 比较,如果相同,再比较 last name。

System.out.printf("%nEmployees in descending order by last name then first:%n");

list.stream().sorted(lastThenFistComp.reversed()).forEach(System.out::println);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值