Today saw a switch codes, I think long and boring, you can optimize it, simply enter the function name as a parameter to transform, somewhat similar to the Strategy pattern.
The following is a simple case of using Java8 behavioral parameterized:
User.java
import lombok.Data; import lombok.ToString; @Data @ToString public class User { public User(Integer age) { this.age = age; } private Integer age; }
UserPredicate.java
public interface CommonPredicate<T> { boolean test(T t); }
Filter.java
import java.util.ArrayList; import java.util.List; public class Filter { /** * list 类型抽象化 * * @param list * @param p * @param <T> * @return */ public static <T> List<T> filter(List<T> list, CommonPredicate<T> p) { List<T> result = new ArrayList<T>(); for (T t : list) { if (p.test(t)) { result.add(t); } } return result; } public List<User> oldUser(List<User> inventory) { return filter(inventory, (User user) -> user.getAge() > 50); } public List<User> youngUser(List<User> inventory) { return filter(inventory, (User user) -> user.getAge() < 20); } public static void main(String[] args) { List<User> userList = new ArrayList<>(); userList.add(new User(11)); userList.add(new User(21)); userList.add(new User(31)); userList.add(new User(41)); userList.add(new User(51)); userList.add(new User(61)); Filter filter = new Filter(); List<User> oldList = filter.oldUser(userList); oldList.forEach(r -> System.out.println(r.toString())); System.out.println("======="); List<User> youngerList = filter.youngUser(userList); youngerList.forEach(y -> System.out.println(y.toString())); } }
The output of Filter.java inside the main method is as follows:
User(age=51) User(age=61) ======= User(age=11)