JDK 8引入了Stream API,它是Java中处理集合数据的一种新方式。Stream流提供了一种更简洁、更灵活的方式来对集合进行操作和处理。
Stream流可以看作是一种高级的迭代器,它可以对集合中的元素进行过滤、映射、排序、聚合等操作,而不需要显式地使用循环。这样可以使代码更加简洁、易读,并且可以充分利用多核处理器的优势。
Stream流的特点包括:
延迟计算:Stream流中的操作是惰性执行的,只有在终止操作时才会触发计算。这种延迟计算的特性可以提高性能,因为只计算需要的结果。
内部迭代:Stream流使用内部迭代器来遍历集合,这意味着不需要显式地编写循环来遍历集合。这样可以提高代码的简洁性和可读性。
支持并行操作:Stream流可以很方便地进行并行操作,即将任务分成多个子任务并行执行,然后将结果合并。这可以提高处理大量数据的效率。
使用Stream流可以大大简化集合数据的处理,使代码更加简洁、易读,并且可以充分发挥多核处理器的优势。
创建Stream流:
Stream流的中间操作:
Stream流的终端操作:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
List<String> filteredNames = names.stream()
.filter(name -> name.length() > 4)
.collect(Collectors.toList());
System.out.println(filteredNames); // 输出:[Alice, Charlie]
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = numbers.stream()
.map(number -> number * number)
.collect(Collectors.toList());
System.out.println(squaredNumbers); // 输出:[1, 4, 9, 16, 25]
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedNumbers); // 输出:[1, 2, 5, 8, 9]
List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers); // 输出:[1, 2, 3, 4, 5]
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> limitedNumbers = numbers.stream()
.limit(3)
.collect(Collectors.toList());
System.out.println(limitedNumbers); // 输出:[1, 2, 3]
List<Integer> skippedNumbers = numbers.stream()
.skip(2)
.collect(Collectors.toList());
System.out.println(skippedNumbers); // 输出:[3, 4, 5]
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean anyMatch = numbers.stream()
.anyMatch(number -> number > 3);
System.out.println(anyMatch); // 输出:true
boolean allMatch = numbers.stream()
.allMatch(number -> number > 0);
System.out.println(allMatch); // 输出:true
boolean noneMatch = numbers.stream()
.noneMatch(number -> number < 0);
System.out.println(noneMatch); // 输出:true
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 输出:15
int max = numbers.stream()
.reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b);
System.out.println(max); // 输出:5
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.forEach(name -> System.out.println("Hello, " + name));
// 输出:
// Hello, Alice
// Hello, Bob
// Hello, Charlie
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Average: " + stats.getAverage());
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
// 输出:
// Count: 5
// Sum: 15
// Average: 3.0
// Max: 5
// Min: 1
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25),
new Person("David", 35),
new Person("Eve", 30)
);
Map<Integer, List<Person>> ageGroups = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(ageGroups);
// 输出:
// {25=[Person{name='Alice', age=25}, Person{name='Charlie', age=25}],
// 30=[Person{name='Bob', age=30}, Person{name='Eve', age=30}],
// 35=[Person{name='David', age=35}]}
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 输出:15
List<List<Integer>> numberLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
List<Integer> flattenedList = numberLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);
// 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstEvenNumber = numbers.stream()
.filter(number -> number % 2 == 0)
.findFirst();
System.out.println(firstEvenNumber); // 输出:Optional[2]
Optional<Integer> anyEvenNumber = numbers.stream()
.filter(number -> number % 2 == 0)
.findAny();
System.out.println(anyEvenNumber); // 输出:Optional[2](可能不同于findFirst的结果)
List<String> names = Arrays.asList("Alice", null, "Bob", null, "Charlie");
List<String> nonNullNames = names.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println(nonNullNames); // 输出:[Alice, Bob, Charlie]
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> uppercaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercaseNames); // 输出:[ALICE, BOB, CHARLIE]