/**
* 员工对象
*/
public class Employ {
private String name;
private Integer age;
private Double salary;
public Employ() {
}
public Employ(String name, Integer age, Double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employ{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
/**
* 过滤接口
*/
public interface MyPredict<T> {
boolean test(T t);
}
/**
* 不同种实现策略
*/
public class FileEmployByAge implements MyPredict<Employ> {
@Override
public boolean test(Employ employ) {
return employ.getAge() >= 35;
}
}
public class Test {
private static List<Employ> list = Arrays.asList(new Employ("张三",18,99999.9),
new Employ("李四",18,3439.9),
new Employ("王五",36,6666.9),
new Employ("赵六",41,7777.9),
new Employ("田七",9,2222.9));
public static void main(String[] args) {
// 获取当前公司中员工中年龄大于35的员工信息
// List<Employ> employs = filterEmploys(list);
// for (Employ employ:employs) {
// System.out.println(employ);
// }
// 获取当前公司中员工中工资大于5000的工资信息
// List<Employ> employs1 = filterEmploys2(list);
// for (Employ employ:employs1) {
// System.out.println(employ);
// }
// 优化方式一 策略模式
// List<Employ> employs = fileEmploy(list, new FileEmployByAge());
// for (Employ employ:employs) {
// System.out.println(employ);
// }
// 优化方式二 匿名内部类
// List<Employ> employs = fileEmploy(list, new MyPredict<Employ>() {
// @Override
// public boolean test(Employ employ) {
// return employ.getSalary() < 5000;
// }
// });
// for (Employ employ:employs) {
// System.out.println(employ);
// }
// 优化方式三 Lambda表达式
// List<Employ> employs = fileEmploy(list, t -> t.getAge() > 35);
// employs.forEach(System.out::println);
// 优化方式四 Stream API
list.stream()
.filter(t->t.getAge()>35)
.limit(1)
.forEach(System.out::println);
list.stream()
.map(Employ::getName)
.forEach(System.out::println);
}
// 优化方式一
public static List<Employ> fileEmploy(List<Employ> list,MyPredict<Employ> myPredict){
List<Employ> list1 = new ArrayList<>();
for (Employ employ:list) {
if (myPredict.test(employ)){
list1.add(employ);
}
}
return list1;
}
// 获取当前公司中员工中工资大于5000的工资信息
public static List<Employ> filterEmploys2(List<Employ> list){
List<Employ> list1 = new ArrayList<>();
for (Employ employ:list) {
if (employ.getSalary() >= 5000){
list1.add(employ);
}
}
return list1;
}
// 获取当前公司中员工中年龄大于35的员工信息
public static List<Employ> filterEmploys(List<Employ> list){
List<Employ> list1 = new ArrayList<>();
for (Employ employ:list) {
if (employ.getAge() >= 35){
list1.add(employ);
}
}
return list1;
}
}