【Java】Stream流
Java Stream 概述
Java 8 新增的 Stream,配合同版本出现的 Lambda ,给我们操作集合(Collection)提供了极大的便利。
什么是 Java Stream
Stream将要处理的元素集合看作一种流,在流的过程中,借助Stream API对流中的元素进行操作,比如:筛选、排序、聚合等。
Stream 可以由数组或集合创建,对流的操作分为以下两种: ❑ 中间操作:每次返回一个新的流,可以有多个。 ❑ 终端操作:每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。
Stream 流的特性
❑ stream 不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
❑ stream 不会改变数据源,通常情况下会产生一个新的集合或一个值。
❑ stream 具有延迟执行特性,只有调用终端操作时,中间操作才会执行。
Stream 的使用分为三个步骤
❑ 创建Stream (使用数据源可以是集合、数组来获取流)
❑ 中间操作 (对数据源的数据进行处理)
❑ 终止操作 (先执行中间操作产生结果后终止流,之后不能再使用该流)
惰性求值 中间操作不会执行任何的处理,而是在终止操作时一次性全部处理,这就是惰性求值
// 像这样的代码并未做什么实际工作 lists.stream().filter(x -> x != 1)
// 像这种有终止操作的代码才会产生新值 List<Integer> list1 = list.parallelStream().filter(x -> x != 1).collect(Collectors.toList());
获取 Stream 的几种方式
获取方式
Stream可以通过集合数组创建。
❑ 通过java.util.Collection.stream()
方法用集合创建流
List<String> list = Arrays.asList("a", "b", "c"); // 创建一个顺序流 Stream<String> stream = list.stream(); // 创建一个并行流 Stream<String> parallelStream = list.parallelStream();
使用java.util.Arrays.stream(T[] array)
方法用数组创建流
int[] array={1,3,5,6,8}; IntStream stream = Arrays.stream(array);
❑ 使用Stream的静态方法:of()
、iterate()
、generate()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6); Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4); stream2.forEach(System.out::println); Stream<Double> stream3 = Stream.generate(Math::random).limit(3); stream3.forEach(System.out::println);
Stream 的使用
提前准备一下初始化数据
List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, "male", "New York")); personList.add(new Person("Jack", 7000, "male", "Washington")); personList.add(new Person("Lily", 7800, "female", "Washington")); personList.add(new Person("Anni", 8200, "female", "New York")); personList.add(new Person("Owen", 9500, "male", "New York")); personList.add(new Person("Alisa", 7900, "female", "New York")); class Person { private String name; // 姓名 private int salary; // 薪资 private int age; // 年龄 private String sex; //性别 private String area; // 地区 // 构造方法 public Person(String name, int salary, int age,String sex,String area) { this.name = name; this.salary = salary; this.age = age; this.sex = sex; this.area = area; } // 省略了get和set }
遍历/匹配(foreach/find/match)
Stream
也是支持类似集合的遍历和匹配元素的,只是Stream
中的元素是以Optional
类型存在的。Stream
的遍历、匹配非常简单。
案例一: 筛选出list集合中大于7的元素,并打印出来
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9); Stream<Integer> stream = list.stream(); stream.filter(x -> x > 7).forEach(System.out::println); } }
案例二: 筛选出intList集合中大于7的元素,并获取第一个 并打印出来
public class StreamTest { public static void main(String[] args) { //注意使用findFirst如果集合里面没有找到数据 会报错 List<Integer> intList = Arrays.asList(6, 7, 3, 8, 1, 2, 9); Optional<Integer> first = intList.stream().filter(item -> item > 7).findFirst(); System.out.println(first.get()); } }
案例三: 筛选员工中工资高于8000的人,并形成新的集合
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName) .collect(Collectors.toList()); System.out.print("高于8000的员工姓名:" + fiterList); } }
案例四: anyMatch/allMatch/noneMatch用法
public class Test04 { public static void main(String[] args) { List<Integer> intList = Arrays.asList(6, 7, 3, 8, 1, 2, 9); //anyMatch 任意一个匹配 boolean b1 = intList.stream().anyMatch(e -> e >= 6); System.out.println(b1); //allMatch 所有都匹配 boolean b2 = intList.stream().allMatch(e -> e >0); System.out.println(b2); //noneMatch 所有都不匹配 boolean b3 = intList.stream().noneMatch(e -> e >100); System.out.println(b3); } }
聚合(max/min/count)
max
、min
、count
这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。
案例一:获取String集合中最长的元素
public class StreamTest { public static void main(String[] args) { List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd"); Optional<String> max = list.stream().max(Comparator.comparing(String::length)); System.out.println("最长的字符串:" + max.get()); } }
案例二:获取员工工资最低的人
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); Optional<Person> min = personList.stream().min(Comparator.comparingInt(Person::getSalary)); System.out.println("员工工资最低值:" + min.get().getSalary()); } }
案例三:计算Integer集合中大于6的元素的个数
import java.util.Arrays; import java.util.List; public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9); long count = list.stream().filter(x -> x > 6).count(); System.out.println("list中大于6的元素个数:" + count); }
映射(map/flatMap)
映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map
和flatMap
两种:
❑ map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
❑ flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
案例一:英文字符串数组的元素全部改为大写。整数数组每个元素+3
public class StreamTest { public static void main(String[] args) { String[] strArr = { "abcd", "bcdd", "defde", "fTr" }; List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList()); List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11); List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList()); System.out.println("每个元素大写:" + strList); System.out.println("每个元素+3:" + intListNew); } }
案例三:将两个字符数组合并成一个新的字符数组
public class StreamTest { public static void main(String[] args) { List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7"); List<String> listNew = list.stream().flatMap(s -> { // 将每个元素转换成一个stream String[] split = s.split(","); Stream<String> s2 = Arrays.stream(split); return s2; }).collect(Collectors.toList()); System.out.println("处理前的集合:" + list); System.out.println("处理后的集合:" + listNew); } }
归约(reduce)
归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
案例一:求集合元素之和
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 1, 23, "male", "New York")); personList.add(new Person("Jack", 1, 25, "male", "Washington")); personList.add(new Person("Lily", 1, 21, "female", "Washington")); personList.add(new Person("Anni", 1, 24, "female", "New York")); personList.add(new Person("Owen", 1, 25, "male", "New York")); personList.add(new Person("Alisa", 1, 26, "female", "New York")); Integer reduce = personList.stream().map(Person::getSalary).reduce(0,Integer::sum); System.out.println(reduce); } }
收集 (collect)
collect
可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。
collect
主要依赖java.util.stream.Collectors
类内置的静态方法。
归集(toList/toSet/toMap)
因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toList
、toSet
和toMap
比较常用,另外还有toCollection
、toConcurrentMap
等复杂一些的用法。
下面用一个案例演示toList
、toSet
和toMap
:
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20); List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000) .collect(Collectors.toMap(Person::getName, p -> p)); System.out.println("toList:" + listNew); System.out.println("toSet:" + set); System.out.println("toMap:" + map); } }
排序 (sorted)
❑ sorted()
:自然排序,流中元素需实现Comparable接口
❑ sorted(Comparator com)
:Comparator排序器自定义排序
public class StreamTest { public static void main(String[] args) { List<Integer> intList = Arrays.asList(6, 7, 3, 8, 1, 2, 9); //升序 List<Integer> collect = intList.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList()); System.out.println(collect); } }
注意事项
Stream 仅可使用一次
一个Stream
流只能被使用一次,使用完成后会自动关闭,重复使用会提示Stream
流已被关闭
public static void main(String[] args) { ArrayList<Integer> integers = new ArrayList<>(); for (int i = 0; i < 10; i++) { integers.add(i); } Stream<Integer> stream = integers.stream(); for (int i = 0; i < 2; i++) { Integer integer = stream.filter(e -> e == 1).findFirst().get(); System.out.println(integer); } } //执行结果如下 Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed