- 需求1:從user集合中 找出age=15的用戶 傳統方法 就不說了 舉例明一下 java1.8 使用Predicate接口解決該需求:
@FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t); }
public static List<User> testPredicate(List<User> users, Predicate<User> predicate) { List<User> tempUsers = new ArrayList<>(); for (User user : users) { boolean test = predicate.test(user); System.out.println(test); if (test) { tempUsers.add(user); } } return tempUsers; }
public static void main(String[] args) { List<User> testPredicate = Test.testPredicate(Test.users, (user) -> user.getAge() == 15); }
Predicate接口中有一個test 接口方法,該方法 可以傳入T 對象 並且返回一個boolean類型 Predicate.test(user) 表示 只有滿足 傳參進去的user 的age=15 才會返回true 則 將該user 添加到tempUsers中
- 需求2:將所有的user對象的age都初始化為0 傳統的可以循環每個user 將該user的age設置為0 java1.8 則可以使用 Consumer 接口實現:
@FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); }
public static List<User> testConsumer(List<User> users, Consumer<User> consumer) { List<User> tempUsers = new ArrayList<>(); for (User user : users) { consumer.accept(user); tempUsers.add(user); } return tempUsers; }
public static void main(String[] args) { List<User> testConsumer = Test.testConsumer(Test.users, (user) -> user.setAge(100)); }
Consumer 有個accept的接口方法,無返回值,可以用作更改對象 consumer.accept(user) 都將執行 user.setAge(100)
3 需求3:返回一個user的姓名 一般都是直接user.getName java1.8 則 用function接口 可以實現,相對這個需求來說 不用funcation 更快,這里就只是為了使用 而使用:
@FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t);
public static String testFunction(User users, Function<User, String> function) { return function.apply(users); }
public static void main(String[] args) { User user = new User("funcation", 25); String testFunction = Test.testFunction(user, (u) -> { return u.getName(); }); System.out.println(testFunction); }
Function<T, R> 該接口泛型 T 你需要修改 或者 操作的對象 R 是你返回的對象 接口方法
R apply(T t); 傳入參數T 對象 返回 R 對象 例子:傳入的是user對象 返回的是String 對象
4.需求4:尷尬的需求,就是返回一個User對象 java1.8 Supplier
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
public static User testSuppler(Supplier<User> supplier) { return supplier.get(); }
public static void main(String[] args) { User testSuppler = Test.testSuppler(() -> new User("Tom", 15)); System.out.println(testSuppler); }
Supplier<T> 返回一個泛型對象。有點類似 工廠方法
5 上面就是 java1.8 常用的幾個接口 簡單的舉了幾個例子,主要是要能舉一反三 學活了。比如泛型T 可以使基本類型 對象類型