Java四大函数式接口
说明是函数接口?
函数式接口: 只有一个方法的接口。
是哪四个?
Consumer<T>
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
表示接受单个输入参数并且不返回结果的操作。
与大多数其他功能界面不同, Consumer预计将通过副作用进行操作。
消费型接口,就是你给我数值,我去做什么事
*/
代码测试说明
public static void main(String[] args) {
User user = new User("xiang", 18);
//输入参数user.name
consumerTest(user,t -> System.out.println("姓名:" + user.getName()));
//输入参数user
consumerTest(user,t ->{
t.setName("zhangsan");
t.setAge(20);
});
System.out.println(user);
}
/**
* 消费型接口,就是你给我数值,我去做什么事
*/
public static void consumerTest(User user, Consumer<User> con) {
con.accept(user);
}
大家可以先猜测一下输出结果????
Function<T,R>
@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 void main(String[] args) {
User user = new User("xiang", 18);
String res = intrFun(user, t -> {
return t;
});
System.out.println(res);
}
/**
* 函数型接口 有参数,可以有返回值
*
* @param user
* @param fn
* @return
*/
public static String intrFun(User user, Function<User, User> fn) {
User user1 = fn.apply(user);
return "姓名:" + user1.getName() + "\t\t年龄:" + user1.getAge();
}
猜猜结果
Predicate<T>
//输入一个参数,返回一个boolean
@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 void main(String[] args) {
List<Integer> list = Arrays.asList(2, 4, 6, 8, 10);
List<Integer> integers = filterInt(list, (val) -> val > 5);
integers.forEach(System.out::println);
}
//需求:将满足条件的字符串,放入集合中
public static List<Integer> filterInt(List<Integer> list, Predicate<Integer> pre){
List<Integer> integers = new ArrayList<>();
for (Integer val : list) {
if(pre.test(val)){
integers.add(val);
}
}
return integers;
}
输出结果
Supplier<T>
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
//无参,返回一个结果
上代码
public static void main(String[] args) {
User user = new User("xiang", 18);
//无输入参数,有返回值
User supplier = supplier(user, () -> {
return user;
});
System.out.println(supplier);
}
/**
* 供给型接口的测试 无参数,有返回值
*/
public static User supplier(User people, Supplier<User> p) {
return p.get();
}
输出结果
学废了吗,反手点个赞!