如何在 Java 9 中的 Stream API 中使用 collect() 方法?
javaobject oriented programmingprogramming更新于 2025/8/10 22:36:17
Stream API 中的 collect() 方法从流对象中收集所有对象并存储在 集合类型 中。用户必须提供可以存储结果的集合类型。我们使用 Collectors Enum 指定集合类型。Collectors Enum 中可以存在不同的类型和不同的操作,但大多数时候我们可以使用 Collectors.toList()、Collectors.toSet() 和 Collectors.toMap()。
语法
<R, A> R collect(Collector<? super T,A,R> collector)
示例
import java.util.*;
import java.util.stream.*;
public class StreamCollectMethodTest {
public static void main(String args[]) {
List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
List<String> subset1 = list.stream()
.takeWhile(s -> !s.equals("e"))
.collect(Collectors.toList());
System.out.println(subset1);
List<String> subset2 = list.stream()
.dropWhile(s -> !s.equals("e"))
.collect(Collectors.toList());
System.out.println(subset2);
List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i+1)
.collect(Collectors.toList());
System.out.println(numbers);
}
}
输出
[a, b, c, d] [e, f, g, h, i] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

