函数式接口
只有一个方法的接口,Runnable接口就是一个典型的函数式接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
函数式接口,简化编程模型,在新版本的框架底层大量应用
四大原生函数式接口
- Consumer
- Function
- Predicate
- Supplier
Function 函数型接口
源码:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
使用:
/**
* 有一个输入参数,一个人输出
*/
public class FunctionTest {
public static void main(String[] args) {
Function<String, String> function = new Function<String, String>() {
@Override
public String apply(String s) {
return s;
}
};
System.out.println(function.apply("aaa"));
}
}
执行结果:
aaa
使用lambda表达式简化:
Function<String, String> function = (str)->{
return str;
};
Predicate 断定型接口
源码:
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
使用:
/**
* 输入一个值,返回布尔值
*/
public class PredicateTest {
public static void main(String[] args) {
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String o) {
return o.isEmpty();
}
};
System.out.println(predicate.test(""));
}
}
执行结果:
true
使用lambda表达式简化:
Predicate<String> predicate = (o)->{
return o.isEmpty();
};
Consumer 消费型接口
源码:
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
使用:
/**
* 只有输入,没有返回值
*/
public class ConsumerTest {
public static void main(String[] args) {
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
consumer.accept("qwe");
}
}
执行结果:
qwe
使用lambda表达式简化:
Consumer<String> consumer = (s)->{
System.out.println(s);
};
Supplier 供给型接口
源码:
@FunctionalInterface
public interface Supplier<T> {
T get();
}
使用:
/**
* 没有参数,只有返回值
*/
public class SupplierTest {
public static void main(String[] args) {
Supplier<String> supplier = new Supplier<String>() {
@Override
public String get() {
return "aaa";
}
};
System.out.println(supplier.get());
}
}
执行结果:
aaa
使用lambda表达式简化:
Supplier<String> supplier = ()->{
return "你好";
};
Stream流式计算
集合、MySQL等本质都是用来存储东西的,计算都应该交给流来操作
/**
* 1 ID是偶数
* 2.年龄必须大于23
* 3.用户名转为大写字母
* 4.用户名字符倒着排序
* 5.只输出一个用户
*
* 只能用一行代码
*/
public class Test {
public static void main(String[] args) {
User user1 = new User(1,"a",21);
User user2 = new User(2,"b",22);
User user3 = new User(3,"c",23);
User user4 = new User(4,"d",24);
User user5 = new User(5,"e",25);
User user6 = new User(6,"f",26);
List<User> users = Arrays.asList(user1, user2, user3, user4, user5, user6);
//链式编程+lambda表达式+函数式接口+Stream流式编程
users.stream()
.filter(user -> {return user.getId()%2==0;})
.filter(user -> {return user.getAge()>23;})
.map(user -> {return user.getName().toUpperCase();})
.sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}