lambda表达式,链式编程,函数式接口,Stream流式计算
# 函数式接口
> 函数式接口:只有一个方法的接口
如:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
经过注解@FunctionalInterface修饰
入参是什么,返回什么
源码:
@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 class FunctionTest {
public static void main(String[] args) {
/*Function<String, String> stringStringFunction = new Function<String, String>() {
@Override
public Object apply(String o) {
return null;
}
};*/
//函数接口可以通过lamada表达式简化
Function<String, String> function = (item)->{return item;};
System.out.println(function.apply("aa"));
}
}
**断定型接口:有一个输入参数,返回值只能是布尔值**
源码
@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 class FunctionTest {
public static void main(String[] args) {
/*Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String s) {
return false;
}
};*/
//使用lambda简化
Predicate<String> predicate = (s)->{return s.isEmpty();};
}
}
**消费者接口 只有入参,没有返回值**
源码
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
示例
public class FunctionTest {
public static void main(String[] args) {
/*Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};*/
Consumer<String> consumer = (s)->{return;};
}
}
**供给型接口 没有参数只有返回值**
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
public class FunctionTest {
public static void main(String[] args) {
/* Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return 1024;
}
};*/
Supplier<Integer> supplier =()->{return 1024;};
System.out.println(supplier.get());
}
}
Stream流式计算
/**
* 现有5个用户,进行筛选
* 1.ID是偶数
* 2.年龄大于23
* 3.用户名转为大写
* 4.用户名字母倒序
* 5.只输出一个用户
*/
public class StreamTest {
public static void main(String[] args) {
User u1 = new User(1,"a",21);
User u2 = new User(2,"b",23);
User u3 = new User(3,"c",25);
User u4 = new User(4,"d",27);
User u5 = new User(5,"e",28);
List<User> users = Arrays.asList(u1, u2, u3, u4, u5);
users.stream()
.filter(u->{return u.getId()%2==0;})
.filter(u->{return u.getAge()>23;})
.map(u->{return u.getName().toUpperCase();})
.sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}