1、函数式接口
函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
public interface PersonSay {
void sayMessage(String message);
}
public static void main(String[] args) {
PersonSay ps = (message) -> {
System.out.println("hello" + message);
};
ps.sayMessage("辣鸡");
}
@FunctionalInterface这个注解可以加也可以不加,加上会好点,加了之后如果这个接口里面还有其他的方法,就会报错
2、stream流
分为中间操作和结束操作
foreach处理
map,映射处理,左边映射成右边
filter:过滤用的,过滤之后需要收集collect
sorted:排序:传入两个数,前面数减去后面数——>正序排列
后面数减去前面数——>倒序排列
distincted:去重。上图有两个120,可以去重处理
reduce:规约,规约之后其实返回的是一个终态
allMatch :所有都要满足才会返回true
anyMatch:任意满足返回true
不用流式处理也可以直接处理数据
正序和倒序处理数据示例:
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("hdx", 16),
new Person("hdx1", 17),
new Person("hdx2", 19),
new Person("hdx3", 147),
new Person("hdx4", 56)
);
//正向排序
persons.sort(Comparator.comparingInt(p->p.age));
persons.forEach(System.out::println);
System.out.println("----------------");
//倒序
persons.sort(Comparator.comparingInt(p->-p.age));
persons.forEach(System.out::println);
}
输出结果:
Person{name='hdx', age=16}
Person{name='hdx1', age=17}
Person{name='hdx2', age=19}
Person{name='hdx4', age=56}
Person{name='hdx3', age=147}
----------------
Person{name='hdx3', age=147}
Person{name='hdx4', age=56}
Person{name='hdx2', age=19}
Person{name='hdx1', age=17}
Person{name='hdx', age=16}
多添加排序:先按照年龄倒序排列,再按名字顺序排
persons.sort(Comparator.comparingInt(Person::getAge).reversed().thenComparing(Person::getName));
并行流:多核同时进行,如果一台机器上还有别的程序需要跑,不建议用并行流,可能会导致别的服务不可用