Java8 内置的四大核心函数式接口
Consumer< T > : 消费型接口 void accept(T t);
消费,有去无回,没有返回值
/**
* 消费型接口
*/
@Test
void test() {
happy(10000,m -> System.out.println("Nugoah喜欢大宝剑,每次消费" + m + "元"));
}
void happy(double money, Consumer<Double> consumer) {
consumer.accept(money);
}
Supplier< T > : 供给型接口 T ger();
/**
* 供给型接口
* 示例:随机产生指定随机数并放入集合
*/
@Test
void test1() {
List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
numList.forEach(System.out::println);
}
public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
Integer n = supplier.get();
list.add(n);
}
return list;
}
Function<T, R> : 函数型接口 R apply(T t);
/**
* 函数型接口
* 需求:处理字符串
*/
@Test
void test2() {
String str = "\t\t\t 我大java威武 ";
String s = strHandler(str, String::trim);//取非空字符串
System.out.println(s);
String s1 = strHandler(s, String::toUpperCase);//转大写
System.out.println(s1);
String s2 = s1.substring(2, 6);//截取字符串
System.out.println(s2);
}
public String strHandler(String str, Function<String, String> function) {
return function.apply(str);
}
Predicate< T > : 断言型接口 boolean test(T t);
/**
* 断言型接口
* 需求:过滤字符串,输出长度大于3的字符串
*/
@Test
void test3() {
List<String> list = Arrays.asList("Hello", "world", "Lambda", "www", "ok");
List<String> strList = filterStr(list, s -> s.length() > 3);
strList.forEach(System.out::println);
}
public List<String> filterStr(List<String> list, Predicate<String> predicate) {
ArrayList<String> strings = new ArrayList<>();
for (String string : list) {
if (predicate.test(string)){
strings.add(string);
}
}
return strings;
}
方法引用:
若Lambda 体中的内容有方法已经实现了,我们可以使用“方法引用”(可以理解为方法引用是Lambda表达式的另外一种表现形式)
主要有三种语法格式:
- 对象::实例方法名
- 类::静态方法名
- 类::实例方法名
Stream的三个操作步骤:
- 创建Stream
- 中间操作
- 终止操作(终端操作)
创建Stream
@Test
void test4() {
// 1.可以通过Collection 系列集合提供的 stream() 或 parallelStream()
ArrayList<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
// 2. 通过 Arrays 中的静态方法 stream() 获取数组流
Employee[] emps = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(emps);
// 3.通过 Stream 类中的静态方法 of()
Stream<String> stream3 = Stream.of("aa", "bb", "cc");
// 4.创建无限流
//迭代
Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
stream4.forEach(System.out::println);
//生成
Stream.generate(() -> Math.random()).forEach(System.out::println);
}
中间操作
筛选与切片
- filter——接收 Lambda ,从流中排除某些元素
- limit——截断流,使其元素不超过给定数量。
- skip(n)——跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补
- distinct——筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素
filte
@Test
// 内部迭代:迭代操作由 Stream API 完成
public void test1() {
// 中间操作:不会执行任何操作
Stream<Employee> stream = employees.stream()
.filter((e) -> {
// 在执行中间操作时,不会执行任何操作(中间操作没有执行)
System.out.println("Stream API 的中间操作")
return e.getAge() > 35;
});
// 终止操作:一次性执行全部内容,即“即惰性求值”
stream.forEach(System.out::println);
}
// 外部迭代:有我们自己完成
@Test
public void test2() {
Iterator<Employee> it = employees.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
limit
@Test
public void test3() {
employees.stream()
.filter((e) -> {
System.out.println("短路!");
return e.getSalary() > 5000;
})
.limit(2)
.forEach(System.out::println);
}
skip(n)
@Test
public void test4() {
employees.stream()
.filter((e) -> e.getSalary() > 5000)
// 扔掉前两个元素,跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补
.skip(2)
.forEach(System.out::println);
}
distinct
@Test
public void test4() {
employees.stream()
.filter((e) -> e.getSalary() > 5000)
.skip(2)
// 筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素
.distinct()
.forEach(System.out::println);
}
注意:筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素
所以,必须重写hashCode() 和 equals() 方法
映射
/**
* 映射
* map -- 接收 Lambda ,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
* flatMap -- 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流
*/
@Test
public void test01() {
List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
list.stream()
.map(String::toUpperCase)//{ {a, a, a} {b, b, b} } ,流里面放流,类似add()
.forEach(System.out::println);
System.out.println("----------------------");
Stream<Stream<Character>> stream = list.stream()
.map(TestStream01::filterCharacter);
stream.forEach((sm) -> sm.forEach(System.out::println));
System.out.println("----------------------");
Stream<Character> sm = list.stream()
.flatMap(TestStream01::filterCharacter);//{a, a, a, b, b, b,...} 把所有的流连接成一个流,类似addAll()
sm.forEach(System.out::println);
}
public static Stream<Character> filterCharacter(String str) {
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}
排序
- sorted() --自然排序(Comparable)
- sorted(Comparator com)-- 定制排序(Comparator)
@Test
public void test7() {
List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd");
list.stream()
.sorted()
.forEach(System.out::println);
System.out.println("------------------------");
employees.stream()
sorted((e1, e2) -> {
if(e1.getAge().equals(e2.getAge())){
return e1.getName().compareTo(e2.getName());
}else{
return e1.getAge().compareTo(e2.getAge());// 升序
return -e1.getAge().compareTo(e2.getAge());// 降序
}
})
}
终止操作
- allMatch – 检查是否匹配所有元素
- anyMatch – 检查是否至少匹配一个元素
- noneMatch – 检查是否没有匹配所有元素
- findFirst – 返回第一个元素
- findAny – 返回当前流中的任意元素
- count – 返回流中元素的总个数
- max – 返回流中最大值
- min – 返回流中最小值
List<Employee> employees = Arrays.asList(
new Employee("张三", 18, 9999.99, Employee.Status.FREE),
new Employee("李四", 58, 5555.55, Employee.Status.BUSY),
new Employee("王五", 26, 3333.33, Employee.Status.VOCATION),
new Employee("赵六", 36, 6666.66, Employee.Status.FREE),
new Employee("田七", 12, 8888.88, Employee.Status.BUSY)
);
@Test
public void test1() {
/*
检查是否匹配所有元素
*/
boolean b1 = employees.stream()
.allMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
System.out.println(b1); // 输出false
/*
检查是否至少匹配一个元素
*/
boolean b2 = employees.stream()
.anyMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
System.out.println(b2);
/*
检查是否没有匹配所有元素
*/
boolean b3 = employees.stream()
.noneMatch(e -> e.getSalary().equals(Employee.Status.BUSY));
System.out.println(b3);
/*
返回第一个元素
*/
Optional<Employee> op = employees.stream() // 如果最终的结果可能为空,则返回Optional
.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(op);
/*
返回当前流中的任意元素
*/
Optional<Employee> op2 = employees.stream()
.filter(e -> e.getStatus().equals(Employee.Status.FREE))
.findAny();
System.out.println(op2);
/*
返回流中元素的个数
*/
long count = employees.stream()
.count();
System.out.println(count);
/*
返回流中元素的最大值
*/
Optional<Employee> max = employees.stream()
.max(Comparator.comparingDouble(Employee::getSalary));
System.out.println(max);
/*
返回流中元素的最小值
*/
Optional<Double> min = employees.stream()
.map(Employee::getSalary) // 经过map映射,流中的数据都变成了Double类型的salary,可以直接使用方法引用
.min(Double::compare);
System.out.println(min.get());
}
规约
List<Employee> employees = Arrays.asList(
new Employee("张三", 18, 9999.99, Employee.Status.FREE),
new Employee("李四", 58, 5555.55, Employee.Status.BUSY),
new Employee("王五", 26, 3333.33, Employee.Status.VOCATION),
new Employee("赵六", 36, 6666.66, Employee.Status.FREE),
new Employee("田七", 12, 8888.88, Employee.Status.BUSY)
);
/**
* 规约
* reduce(T identity, BinaryOperator) / reduce(BinaryOperator) -- 可以将流中元素反复结合起来,得到一个值
* 起始值 二元运算
*/
@Test
public void test2() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Integer num = list.stream()
.reduce(0, (x, y) -> x + y);
// .reduce(0, Integer::sum)
System.out.println(num);
Optional<Double> op = employees.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
收集
/**
* 收集
* collect -- 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
*/
@Test
public void test3() {
List<String> list = employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("-----------------------");
HashSet<String> hs = employees.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
}
@Test
public void test4() {
// 总数
Long count = employees.stream()
.collect(Collectors.counting());
System.out.println(count);
System.out.println("-----------------");
// 平均值
Double avg = employees.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
System.out.println("------------------");
// 总和
Double sum = employees.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
//工资最大的成员
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(max.get());
//最小工资
Optional<Double> min = employees.stream()
.map(Employee::getSalary)
.collect(Collectors.minBy(Double::compare));
System.out.println(min.get());
}
// 多级分组
@Test
public void test5() {
Map<Employee.Status, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() <= 35) {
return "青年";
} else if (e.getAge() <= 50) {
return "中年";
} else {
return "老年";
}
})));
map.forEach((key, value) -> System.out.println(key + ":" + value));
}
// 分区
@Test
public void test6() {
Map<Boolean, List<Employee>> map = employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
map.forEach((key, value) -> System.out.println(key + "::" + value));
}
@Test
public void test7() {
DoubleSummaryStatistics dds = employees.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dds.getSum());
System.out.println(dds.getAverage()); // 平均值
System.out.println(dds.getMax());
}
@Test
public void test8() {
String str = employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(",", "===", "==="));
System.out.println(str);
}