JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景它們主要在java.util.function包中被提供。
我們介紹幾種最常用的
一.內置函數Consumer
源碼是這樣的[無返回值]
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
測試代碼
/**
* TODO 類描述
*
* @author honghe
*/
public class Demo {
public static void main(String[] args) {
User user1 = new User("admin",11,"男");
Consumer<User> user2 = user -> user.setAge(0);
user2.accept(user1);
System.out.println("admin的age = [" + user1.getAge() + "]");
//結果爲 admin的age = [0]
}
}
二.內置函數Supplier
源碼是這樣的[有個範型返回值]
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
測試代碼
/**
* TODO 類描述
*
* @author honghe
*/
public class Demo {
//循環10次生成userList 年齡爲每次循環的點值
public static void main(String[] args) {
List<User> userList = getUserList(5,()->new User("admin",100,"男") );
for (User u: userList) {
System.out.println("姓名 = [" + u.getName() + "]年齡 = ["+u.getAge()+"]");
}
}
public static List<User> getUserList(Integer sum,Supplier<User> userSupplier){
List<User> userList=new ArrayList<>();
for (int i = 0; i <sum ; i++) {
User user = userSupplier.get();
user.setAge(i);
userList.add(user);
}
return userList;
}
}
二.內置函數Function
/**
* TODO 類描述
*
* @author honghe
*/
public class Demo {
public static void main(String[] args) {
String hello = strChange("Hello", (str)->str.toLowerCase());
System.out.println(hello);
String subStr = strChange("這是Function的測試代碼", (str)->str.substring(5,14));
System.out.println(subStr);
}
private static String strChange(String str,Function<String,String> fun){
return fun.apply(str);
}
}
二.內置函數Predicate
描述:Predicate< T>接口接受一個T類型參數,返回一個boolean值。
源代碼
public interface Predicate<T> {
boolean test(T t);
}
測試代碼
/**
* TODO 類描述
*
* @author honghe
*/
public class Demo {
//判斷是否大於特定的需求 >5
public static void main(String[] args) {
Predicate<Integer> boolValue = x -> x>5;
Integer num1 = 1;
Boolean flag1 = boolValue.test(num1);
Integer num2 = 6;
Boolean flag2 = boolValue.test(num2);
System.out.println("flag1 = [" + flag1 + "]");// false
System.out.println("flag2 = [" + flag2 + "]");// true
}
}