filter, map, flatmap, limit, skip, sort, distinct, collect, reduce, summary statistics
public class StreamTest {
public static void main(String[] args) {
//filter
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> filteredStream = stream.filter(n -> n % 2 == 0); // 过滤出偶数
// filteredStream.forEach(System.out::println);
//map
Stream<String> stream2 = Stream.of("apple", "banana", "cherry");
Stream<Integer> mappedStream = stream2.map(String::length); // 映射为单词长度
// mappedStream.forEach(System.out::println);
//flatmap
List<List<Integer>> nestedList = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
Stream<Integer> flattenedStream = nestedList.stream().flatMap(List::stream);
// flattenedStream.forEach(System.out::println);
//limit
Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> limitedStream = stream3.limit(3); // 只保留前 3 个元素
// limitedStream.forEach(System.out::println);
//skip
Stream<Integer> stream4 = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> skippedStream = stream4.skip(2); // 跳过前 2 个元素
// skippedStream.forEach(System.out::println);
//sort
Stream<Integer> stream5 = Stream.of(5, 2, 4, 1, 3);
Stream<Integer> sortedStream = stream5.sorted(); // 自然顺序排序
// sortedStream.forEach(System.out::println);
//distinct
Stream<Integer> stream6 = Stream.of(1, 2, 2, 3, 3, 3);
Stream<Integer> distinctStream = stream6.distinct(); // 去重
// distinctStream.forEach(System.out::println);
//collect
Stream<String> stream7 = Stream.of("apple", "banana", "cherry");
List<String> collectedList = stream7.toList(); // 收集为 List
// collectedList.forEach(System.out::println);
//reduce 规约
Stream<Integer> stream8 = Stream.of(1, 2, 3, 4, 5);
Optional<Integer> sum = stream8.reduce(Integer::sum); // 对所有元素求和
// System.out.println("sum: " + sum);
//summary statistics
IntStream stream9 = IntStream.of(1, 2, 3, 4, 5);
IntSummaryStatistics stats = stream9.summaryStatistics();
System.out.println("Count: " + stats.getCount());
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getSum());
System.out.println("Average: " + stats.getAverage());
}
}