1.Stream的创建:
// 从集合创建Stream
List numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream streamFromList = numbers.stream();
// 从数组创建Stream
String[] words = {"Hello", "World", "Java"};
Stream streamFromArray = Arrays.stream(words);
// 使用Stream.of()创建Stream
Stream streamOfValues = Stream.of(1, 2, 3, 4, 5);
// 创建一个无限流
Stream infiniteStream = Stream.iterate(0, n -> n + 1);
2.中间操作:
List numbers = Arrays.asList(1, 2, 3, 4, 5);
// filter():筛选
Stream filteredStream = numbers.stream()
.filter(n -> n % 2 == 0);
// map():转换
Stream mappedStream = numbers.stream()
.map(n -> "Number: " + n);
// sorted():排序
Stream sortedStream = numbers.stream()
.sorted();
// distinct():去重
Stream distinctStream = numbers.stream()
.distinct();
// limit():限制元素个数
Stream limitedStream = numbers.stream()
.limit(3);
// skip():跳过元素
Stream skippedStream = numbers.stream()
.skip(2);
3. 最终操作:
List numbers = Arrays.asList(1, 2, 3, 4, 5);
// forEach():遍历每个元素
numbers.stream()
.forEach(System.out::println);
// toArray():转换为数组
Object[] numberArray = numbers.stream()
.toArray();
// collect():收集到集合或映射中
List numberList = numbers.stream()
.collect(Collectors.toList());
Set numberSet = numbers.stream()
.collect(Collectors.toSet());
Map numberMap = numbers.stream()
.collect(Collectors.toMap(n -> n, n -> "Number: " + n));
// reduce():聚合操作
Optional sum = numbers.stream()
.reduce((a, b) -> a + b);
int max = numbers.stream()
.reduce(Integer.MIN_VALUE, Integer::max);
// anyMatch()、allMatch()、noneMatch():元素匹配判断
boolean anyMatch = numbers.stream()
.anyMatch(n -> n > 3);
boolean allMatch = numbers.stream()
.allMatch(n -> n > 0);
boolean noneMatch = numbers.stream()
.noneMatch(n -> n < 0);
// findFirst()、findAny():查找元素
Optional first = numbers.stream()
.findFirst();
Optional any = numbers.stream()
.findAny();
// count():元素数量
long count = numbers.stream()
.count();
4.分组和分区:
List people = Arrays.asList(
new Person("John", 30),
new Person("Jane", 25),
new Person("Mary", 30),
new Person("Mark", 28),
new Person("Alice", 25)
);
// 按年龄分组
Map> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// 按年龄分区
Map> peopleByAgePartition = people.stream()
.collect(Collectors.partitioningBy(person -> person.getAge() > 25));
5.并行流操作:
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 使用并行流求和
int sum = numbers.parallelStream()
.reduce(0, Integer::sum);
// 使用并行流过滤条件
List filteredNumbers = numbers.parallelStream()
.filter(n -> n > 5)
.collect(Collectors.toList());