java8新特性
1.函数式接口
之前的匿名内部类方式:
接口
interface MyInter {
int max(int a, int b);
}
匿名内部类
MyInter myInter = new MyInter() {
@Override
public int max(int a, int b) {
return a > b ? a : b;
}
};
System.out.println(myInter.max(5,6));
使用Lambda后
MyInter myInter = (a, b) -> {
return a > b ? a : b;
};
System.out.println(myInter.max(5, 6));
口诀:复制小括号,写死大箭头,落地大括号
- 注意事项:
1. 使用函数式接口需要在接口上添加@FunctionalInterface注解
2. 接口里只可定义一个未实现方法。
3.可以定义多个默认方法或者静态方法. - 简写:
1.若只有一个参数,则可以省略小括号
2. 函数中若只有一行代码,可以省略retun,去掉大括号
@FunctionalInterface
interface MyInter {
int max(int a, int b);
default void man(int a, int b ){
}
default void mbn(int a, int b ){
}
static void mcn(int a, int b ){
}
static void mdn(int a, int b ){
}
}
2.四大函数式接口
由于使用Lanmdba需要函数式接口,而每次使用时定义比较麻烦,java8提供了4中常用行内置函数式接口
1.函数型接口
2个参数:传入一个自定义参数T,返回自定义参数R
实现方法 apply()
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function<String ,String> function = a ->{
return a;
};
System.out.println(function.apply("hahaa"));
2.断定型接口
1个参数:传入一个自定义参数T,返回 boolean 类型
实现方法 Test()
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);}
Predicate<Integer> predicate = i -> i > 0 ? true:false;
System.out.println(predicate.test(2));
3.消费型接口
1个参数:传入一个自定义参数T,无返回
实现方法 accept()
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);}
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("hello");
4.供给型接口
1个参数:传入返回 值类型
实现方法 get()
@FunctionalInterface
public interface Supplier<T> {
T get();
}
Supplier supplier = ()-> {
return "hahaha";
};
System.out.println(supplier.get());
3.stream
过滤:用来筛选
Stream<T> filter(Predicate<? super T> predicate);
转化为map集合
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
map转为list
collect(Collectors.toList())
显示几条,类似mysql分页
Stream<T> limit(long maxSize)
排序:实现Comparator接口
Stream<T> sorted(Comparator<? super T> comparator)
案例
//按照给出数据,找到 id 是偶数,年龄大于24。并将其 用户名大写,排序,只显示一条
User user1 = new User(11, "a", 23);
User user2 = new User(12, "b", 24);
User user3 = new User(13, "c", 22);
User user4 = new User(14, "d", 28);
User user5 = new User(16, "e", 26);
List<User> list = Arrays.asList(user1, user2, user3, user4, user5);
list.stream().filter(user -> user.getId() %2 == 0) //id是偶数;
.filter(user -> user.getAge() > 24) //年龄大于24
.map(user -> user.getName().toUpperCase()) //大写
.sorted((u1,u2) -> u2.compareTo(u1)) //排序
.limit(1)
.forEach(System.out::println);
}
浙公网安备 33010602011771号