目录
提示:List<String> stringList = new ArrayList<>();
// stringList在经过stream()流方法之后,会生成一个新的list集合或新的数据源
以下写入了关于Stream API在多种情况下使用的案例:
1、Stream API
中间操作
过滤(Filter):
List<String> filteredList = stringList.stream()
.filter(s -> s.length() > 5)
.collect(Collectors.toList());
映射(Map):
List<Integer> lengths = stringList.stream()
.map(String::length)
.collect(Collectors.toList());
扁平映射(FlatMap):
List<String> flatMapList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
去重(Distinct):
List<String> distinctList = stringList.stream()
.distinct()
.collect(Collectors.toList());
排序(Sorted):
List<String> sortedList = stringList.stream()
.sorted()
.collect(Collectors.toList());
终端操作
收集(Collect):
List<String> collectedList = stringList.stream()
.collect(Collectors.toList());
计数(Count):
long count = stringList.stream()
.count();
聚合(Reduce):
Optional<String> concatenated = stringList.stream()
.reduce((s1, s2) -> s1 + s2);
遍历(ForEach):
stringList.stream()
.forEach(System.out::println);
匹配(Match):
boolean anyMatch = stringList.stream()
.anyMatch(s -> s.startsWith("a"));
查找(Find):
Optional<String> found = stringList.stream()
.filter(s -> s.length() > 5)
.findFirst();
并行流(Parallel Stream):
List<String> parallelList = stringList.parallelStream()
.filter(s -> s.startsWith("a"))
.collect(Collectors.toList());
2、在Java中的使用
在Java中,Stream API可以应用于集合(Collection)类,数组以及其他数据源。以下是一些在Java中使用Stream API的典型情况:
这些示例演示了Stream API在不同场景下的使用方式。Stream API的强大之处在于它提供了一种声明性的、函数式的处理方式,使得代码更具表达力和可读性。根据具体的业务需求,可以使用不同的中间操作和终端操作来构建复杂的数据处理流程。
集合类上的Stream操作
1. 对List进行过滤和收集
List<String> stringList = Arrays.asList("apple", "banana", "orange", "grape", "watermelon");
List<String> filteredList = stringList.stream()
.filter(s -> s.length() > 5)
.collect(Collectors.toList());
2. 对Map进行操作
Map<Integer, String> numberMap = Map.of(1, "one", 2, "two", 3, "three");
List<String> values = numberMap.values().stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
数组上的Stream操作
1. 对数组进行过滤和收集
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> evenNumbers = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.boxed()
.collect(Collectors.toList());
文件处理
1. 读取文件行并进行操作
Path filePath = Paths.get("example.txt");
try (Stream<String> lines = Files.lines(filePath)) {
List<String> filteredLines = lines.filter(line -> line.contains("Java"))
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
其他数据源
1. 使用Stream生成一系列数字
List<Integer> numberList = Stream.iterate(0, n -> n + 2)
.limit(5)
.collect(Collectors.toList());
2. 使用Stream生成随机数
List<Double> randomNumbers = new Random().doubles(5)
.boxed()
.collect(Collectors.toList());