过滤:stream.filter(predicate)
映射:stream.map(mapper)
排序:stream.sorted(comparator)
去重:stream.distinct()
截断:stream.limit(n)
跳过:stream.skip(n)
并行处理:stream.parallel()
终端操作:
遍历:stream.forEach(action)
收集:stream.collect(collector)
转换为数组:stream.toArray()
转换为List:stream.collect(Collectors.toList())
转换为Set:stream.collect(Collectors.toSet())
转换为Map:stream.collect(Collectors.toMap(keyMapper, valueMapper))
聚合操作:stream.reduce(identity, accumulator)
匹配操作:stream.anyMatch(predicate), stream.allMatch(predicate), stream.noneMatch(predicate)
统计操作:stream.count(), stream.min(comparator), stream.max(comparator), stream.average(), stream.sum()
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Map<String, Integer> nameLengthMap = names.stream()
.collect(Collectors.toMap(name -> name, name -> name.length()));
System.out.println(nameLengthMap); // 输出: {Alice=5, Bob=3, Charlie=7}
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
int min = numbers.stream().min(Comparator.naturalOrder()).orElse(0);
int max = numbers.stream().max(Comparator.naturalOrder()).orElse(0);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(count); // 输出: 5
System.out.println(min); // 输出: 1
System.out.println(max); // 输出: 5
System.out.println(average); // 输出: 3.0
System.out.println(sum); // 输出: 15