User实体类:
public class User {
private String name;
private int age;
private double salary;
//省略无参、有参构造方法、get、set、toString()
}
数据如下:
List<User> usersList = Arrays.asList(
new User("zhangsan",18,999.99),
new User("lisi",38,999.99),
new User("wangwu",50,999.99),
new User("zhaoliu",16,999.99),
new User("tianqi",8,999.99)
);
现在有如下需求:
//需求:获取当前公司中员工年龄大于35的员工信息
public List<User> filterUser(List<User> lists){
List<User> result = new ArrayList<>();
for (User user : lists) {
if(user.getAge()>=35){
result.add(user);
}
}
return result;
}
@Test
public void testUser(){
List<User> userList = filterUser(this.usersList);
for (User user : userList) {
System.out.println(user);
}
}
//需求:获取当前公司中员工工资大于500的员工信息 -----又要重复上面的方法
public List<User> filterUserBySa(List<User> lists){
List<User> result = new ArrayList<>();
for (User user : lists) {
if(user.getSalary()>=500){
result.add(user);
}
}
return result;
}
缺点:每当有类似的需求时,都需要单独写一个方法,提供以下几种优化方式:
优化方式一:策略设计模式
(1)新建一个策略接口
public interface MyPredicate<T> {
public boolean test(T t);
}
(2)两个策略类实现上述接口
public class FilterUserByAge implements MyPredicate<User> {
@Override
public boolean test(User user) {
return user.getAge()>=35;
}
}
public class FilterUserBySalary implements MyPredicate<User> {
@Override
public boolean test(User user) {
return user.getSalary()>=500;
}
}
(3)
public List<User> filterUser(List<User> lists, MyPredicate<User> mp){
ArrayList<User> users = new ArrayList<>();
for (User user : lists) {
if(mp.test(user)){
users.add(user);
}
}
return users;
}
@Test
public void test4(){
List<User> users = filterUser(this.usersList, new FilterUserByAge());
for (User user : users) {
System.out.println(user);
}
System.out.println("=========================================");
List<User> list = filterUser(this.usersList, new FilterUserBySalary());
for (User user : list) {
System.out.println(user);
}
}
优化方式二:匿名内部类
public List<User> filterUser(List<User> lists, MyPredicate<User> mp){
ArrayList<User> users = new ArrayList<>();
for (User user : lists) {
if(mp.test(user)){
users.add(user);
}
}
return users;
}
@Test
public void test5(){
List<User> users = filterUser(this.usersList, new MyPredicate<User>() {
@Override
public boolean test(User user) {
return user.getAge() >= 50;
}
});
for (User user : users) {
System.out.println(user);
}
}
优化方式三:Lambda表达式
public List<User> filterUser(List<User> lists, MyPredicate<User> mp){
ArrayList<User> users = new ArrayList<>();
for (User user : lists) {
if(mp.test(user)){
users.add(user);
}
}
return users;
}
@Test
public void test6(){
List<User> users = filterUser(this.usersList, (e)-> e.getAge() >= 35);
for (User user : users) {
System.out.println(user);
}
}
优化方式四:Stream API
@Test
public void test7(){
users.stream()
.filter((e) -> e.getSalary()>500)
.limit(2) //取前两个
.forEach(System.out::println);
System.out.println("==================================");
users.stream()
.map(User::getName)
.forEach(System.out::println);
}