1.Stream流概念
Stream流是Java 8中引入的一个新的抽象概念,它代表着一种对数据元素进行连续而有序的序列操作的源。Stream可以用来对集合、数组或其他数据源进行函数式编程风格的操作。
2.特点
-
Stream不存储数据元素,它只是对数据源进行操作。这意味着它可以更高效地处理大量的数据。
-
Stream提供了一系列函数式风格的操作方法,例如filter、map、reduce等,可以对流中的数据进行处理和转换。
-
Stream的操作可以是串行的,也可以是并行的。通过并行操作,可以有效地利用多核处理器的能力。
-
Stream操作是惰性求值的。这意味着在终止操作之前,中间的操作不会立即执行,提高了效率。
-
Stream不可复用,对一个已经进行过终端操作的流再次调用,会抛出异常。
3.创建Stream流
- 从集合创建:
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
- 从数组创建:
Stream<String> stream = Stream.of("a", "b", "c");
- 使用生成器:
Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 1);
4.Stream常见方法
4.1 中间操作
- filter():过滤
// 过滤掉以a开头的数据
List<String> res = list.stream().filter(s -> s.startsWith("a"))
.collect(Collectors.toList());
- map():映射
// 对集合中的每个数据加1
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list = list.stream().map(i -> i + 1).collect(Collectors.toList());
- distinct():去重
// 去除集合中的重复数据
list = list.stream().distinct().collect(Collectors.toList());
- limit():截取
// 拿集合中的前2个数据
list = list.stream().limit(2).collect(Collectors.toList());
- skip():跳过某个数据
// 拿集合中的前2个数据,再去掉这两个中的第一个
list = list.stream().limit(2).skip(1).collect(Collectors.toList());
- sorted():自然排序
// sortedList 结果为 ["apple", "banana", "orange"]
List<String> list = Arrays.asList("banana", "apple", "orange");
List<String> sortedList = list.stream().sorted().collect(Collectors.toList());
- sorted(Comparator<? super T> comparator):比较器排序
// sortedList 结果为 ["apple", "banana", "orange"]
List<String> list = Arrays.asList("banana", "apple", "orange");
List<String> sortedList = list.stream()
.sorted(Comparator.comparing(String::length)) // 按字符串长度排序
.collect(Collectors.toList());
4.2 终端操作
- forEach():遍历
// 打印集合元素
list.stream().forEach(System.out::println);
- collect():收集
// 收集成集合
List<String> collected = list.stream().collect(Collectors.toList());
- reduce():累加
// 集合中的年龄相加:
int sum = list.stream().map(Person::getAge).reduce(0, Integer::sum);
// BigDecimal计算,将集合中所有商品的价格累加
BigDecimal totalPrice = goodList.stream()
.map(GoodsCode::getPrice())
.reduce(BigDecimal.ZERO, BigDecimal::add);
- count():总个数
// 返回集合总个数
long count = list.stream().count();
- min() / max():最大/最小值
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35),
new Person("Diana", 20)
);
// 最年轻的人 Diana, Age: 20
Optional<Person> youngest = people.stream().min(Comparator.comparingInt(Person::getAge));
// 最年长的人 Charlie, Age: 35
Optional<Person> oldest = people.stream().max(Comparator.comparingInt(Person::getAge));
- anyMatch():任意一个符合条件
// 是否存在一个 person 对象的 age 等于 20
boolean b = list.stream().anyMatch(person -> person.getAge() == 20);
- allMatch():全部符合条件
// 是否列表中全部对象的 age 等于 20
boolean b = list.stream().allMatch(person -> person.getAge() == 20);
- noneMatch():没有一个元素符合条件
// 是否列表中全部对象的 age 都不等于 20
boolean b = list.stream().noneMatch(person -> person.getAge() == 20);