java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamExamples {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig", "grape");
// 过滤:保留长度大于5的字符串
List<String> filtered = strings.stream()
.filter(s -> s.length() > 5)
.collect(Collectors.toList());
System.out.println("Filtered: " + filtered);
// 映射:将所有字符串转换为大写
List<String> mapped = strings.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Mapped: " + mapped);
// 排序:按字母顺序排序
List<String> sorted = strings.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted: " + sorted);
// 统计:计算字符串的总长度
int totalLength = strings.stream()
.mapToInt(String::length)
.sum();
System.out.println("Total Length: " + totalLength);
// 查找:找到第一个以字母 'c' 开头的字符串
Optional<String> firstWithC = strings.stream()
.filter(s -> s.startsWith("c"))
.findFirst();
firstWithC.ifPresent(s -> System.out.println("First with 'c': " + s));
// 分组:按字符串长度分组
Map<Integer, List<String>> groupedByLength = strings.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println("Grouped by Length: " + groupedByLength);
// 连接:将所有字符串连接成一个字符串,使用逗号分隔
String joined = strings.stream()
.collect(Collectors.joining(", "));
System.out.println("Joined: " + joined);
// 去重:去除重复的字符串
List<String> distinct = strings.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct: " + distinct);
// 限制:限制结果数量为3
List<String> limited = strings.stream()
.limit(3)
.collect(Collectors.toList());
System.out.println("Limited: " + limited);
// 跳过:跳过前3个元素
List<String> skipped = strings.stream()
.skip(3)
.collect(Collectors.toList());
System.out.println("Skipped: " + skipped);
}
}