java Stream API的使用
1、Stream API 介绍
2、为什么要使用 Stream API
3、什么是 Stream
- Stream 自己不会存储元素。
- Stream 不会改变源对象。相反,他们会返回一个持有结果的新 Stream。
- Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
4、Stream 的操作三个步骤
- 创建 Stream 一个数据源 (如: 集合、数组),获取一个流
- 中间操作 一个中间操作链,对数据源的数据进行处理
- 终止操作 (终端操作) 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
4.1 创建 Stream 的方式
声明,首先定义一个类结构:
public class Employee { private int id; private String name; private int age; private double salary; }
- default Stream stream() : 返回一个顺序流
- default Stream parallelStream() : 返回一个并行流
public void test1(){ List<Employee> employees = EmployeeData.getEmployees();// default Stream<E> stream() : 返回一个顺序流
Stream<Employee> stream = employees.stream();// default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
}
- static Stream stream(T[] array): 返回一个流
- public static IntStream stream(int[] array)
- public static LongStream stream(long[] array)
- public static DoubleStream stream(double[] array)
public void test2(){ int[] arr = new int[]{1,2,3,4,5,6}; //调用 Arrays 类的 static <T> Stream<T> stream(T[] array): 返回一个流 IntStream stream = Arrays.stream(arr);Employee e1 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Employee(1001,"Tom"<span style="color: rgba(0, 0, 0, 1)">); Employee e2 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Employee(1002,"Jerry"<span style="color: rgba(0, 0, 0, 1)">); Employee[] arr1 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Employee[]{e1,e2}; Stream</span><Employee> stream1 =<span style="color: rgba(0, 0, 0, 1)"> Arrays.stream(arr1);
}
- public static Stream of(T... values) : 返回一个流
public void test3(){ Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);}
- 迭代 public static Stream iterate(final T seed, final UnaryOperator f)
- 生成 public static Stream generate(Supplier s)
public void test4(){// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//遍历前 10 个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
4.2 Stream 的中间操作
方法
|
描述
|
filter(Predicate p)
|
接收 Lambda , 从流中排除某些元素
|
distinct()
|
筛选,通过流所生成元素的 hashCode()和 equals() 去除重复元素
|
limit(long maxSize)
|
截断流,使其元素不超过给定数量
|
skip(long n)
|
跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一 个空流。与 limit(n) 互补
|
public void test1(){ List<Employee> list =....//自行补充 // filter(Predicate p)——接收 Lambda , 从流中排除某些元素。 Stream<Employee> stream = list.stream(); //练习:查询员工表中薪资大于 7000 的员工信息 stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);System.out.println();
// limit(n)——截断流,使其元素不超过给定数量。
list.stream().limit(3).forEach(System.out::println);
System.out.println();// skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
list.stream().skip(3).forEach(System.out::println);System.out.println();
// distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.stream().distinct().forEach(System.out::println);
方法
|
描述
|
map(Function f)
|
接收一个函数作为参数,该函数会被应用到每个元 素上,并将其映射成一个新的元素。
|
mapToDouble(ToDoubleFunction f)
|
接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。
|
mapToInt(ToIntFunction f)
|
接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 IntStream。
|
mapToLong(ToLongFunction f)
|
接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 LongStream。
|
flatMap(Function f)
|
接收一个函数作为参数,将流中的每个值都换成另
一个流,然后把所有流连接成一个流
|
public void test2(){ // map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。 List<String> list = Arrays.asList("aa", "bb", "cc", "dd"); list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);// 获取员工姓名长度大于 3 的员工的姓名。
List<Employee> employees = EmployeeData.getEmployees();
Stream<String> namesStream = employees.stream().map(Employee::getName);
namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
streamStream.forEach(s ->{
s.forEach(System.out::println);
});
System.out.println();
// flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
characterStream.forEach(System.out::println);}
//将字符串中的多个字符构成的集合转换为对应的 Stream 的实例
public static Stream<Character> fromStringToStream(String str){//aa
ArrayList<Character> list = new ArrayList<>();
for(Character c : str.toCharArray()){
list.add(c);
}
return list.stream();
}
方法
|
描述
|
sorted()
|
产生一个新流,其中按自然顺序排序
|
sorted(Comparator com)
|
产生一个新流,其中按比较器顺序排序
|
public void test4(){ // orted()——自然排序 List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7); list.stream().sorted().forEach(System.out::println); // sorted(Comparator com)——定制排序 //按照年龄排序,相同则按照收入反向排序 employees.stream().sorted( (e1,e2) -> {</span><span style="color: rgba(0, 0, 255, 1)">int</span> ageValue =<span style="color: rgba(0, 0, 0, 1)"> Integer.compare(e1.getAge(),e2.getAge()); </span><span style="color: rgba(0, 0, 255, 1)">if</span>(ageValue != 0<span style="color: rgba(0, 0, 0, 1)">){ </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ageValue; }</span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{ </span><span style="color: rgba(0, 0, 255, 1)">return</span> -<span style="color: rgba(0, 0, 0, 1)">Double.compare(e1.getSalary(),e2.getSalary()); } }).forEach(System.out::println); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">按照年龄排序</span> employees.stream().sorted( (e1,e2) -><span style="color: rgba(0, 0, 0, 1)"> Integer.compare(e1.getAge(),e2.getAge())).forEach(System.out::println);
}
4.3 Stream 的终止操作
- 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。
- 流进行了终止操作后,不能再次使用。
方法
|
描述
|
allMatch(Predicate p)
|
检查是否匹配所有元素
|
anyMatch(Predicate p)
|
检查是否至少匹配一个元素
|
noneMatch(Predicate p)
|
检查是否没有匹配所有元素
|
find First() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中元素总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 内部迭代 (使用 Collection 接口需要用户去做迭代, 称为外部迭代。相反,Stream API 使用内部迭 代——它帮你把迭代做了) |
public void test1(){ List<Employee> list =....//自行补充// llMatch(Predicate p)——检查是否匹配所有元素。
// 练习:是否所有的员工的年龄都大于 18
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
System.out.println(allMatch);// anyMatch(Predicate p)——检查是否至少匹配一个元素。
// 练习:是否存在员工的工资大于 10000
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
System.out.println(anyMatch);// noneMatch(Predicate p)——检查是否没有匹配的元素。
// 练习:是否存在员工姓“雷”
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
System.out.println(noneMatch);
// findFirst——返回第一个元素
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
// findAny——返回当前流中的任意元素
Optional<Employee> employee1 = employees.parallelStream().findAny();
System.out.println(employee1);</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> count——返回流中元素的总个数</span> <span style="color: rgba(0, 0, 255, 1)">long</span> count = employees.stream().filter(e -> e.getSalary() > 5000<span style="color: rgba(0, 0, 0, 1)">).count(); System.out.println(count);
// max(Comparator c)——返回流中最大值
// 练习:返回最高的工资:
Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
Optional<Double> maxSalary = salaryStream.max(Double::compare);
System.out.println(maxSalary);
// min(Comparator c)——返回流中最小值
// 练习:返回最低工资的员工
Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(employee);
System.out.println();
// forEach(Consumer c)——内部迭代
employees.stream().forEach(System.out::println);</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">使用集合的遍历操作</span>
employees.forEach(System.out::println);
}
方法
|
描述
|
reduce(T iden, BinaryOperator b)
|
可以将流中元素反复结合起来,得到一 个值。返回 T
|
reduce(BinaryOperator b)
|
可以将流中元素反复结合起来,得到一 个值。返回 Optional
|
public void test3(){ // reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T // 练习 1:计算 1-10 的自然数的和 List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); Integer sum = list.stream().reduce(0, Integer::sum); System.out.println(sum);// reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
// 练习 2:计算公司所有员工工资的总和
List<Employee> list =....//自行补充
Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
// Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);
System.out.println(sumMoney.get());
}
方法
|
描述
|
collect(Collector c)
|
将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总 的方法
|
方法
|
返回类型
|
作用
|
toList
|
List<T>
|
把流中元素收集到 List
|
List emps= list.stream().collect(Collectors.toList());
|
||
toSet
|
Set<T>
|
把流中元素收集到 Set |
Set emps= list.stream().collect(Collectors.toSet());
|
||
toCollection
|
Collection<T>
|
把流中元素收集到创建的集合 |
Collection emps =list.stream().collect(Collectors.toCollection(ArrayList::new));
|
||
。。。。。。
|
public void test4(){ // collect(Collector c)——将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总的方法 // 练习 1:查找工资大于 6000 的员工,结果返回为一个 List 或 Set List<Employee> list =....//自行补充 List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList()); employeeList.forEach(System.out::println); System.out.println(); Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet()); employeeSet.forEach(System.out::println); }
总结
上文只是简单的介绍了一下 Java 8 中 Stream API 的一些简单的使用,实际工作中还要多多加以练习。