这是一个Java 8 中,如何通过Collectors.toList
方法将Stream
转换到List
的例子。
Java8Example1.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Example1 {
public static void main(String[] args) {
Stream<string> language = Stream.of("java", "python", "node");
//Convert a Stream to List
List<string> result = language.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
output
java
python
node
再举一个例子,过滤数字3并把这个流转换成一个列表。
Java8Example2.java
package com.mkyong.java8;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8Example2 {
public static void main(String[] args) {
Stream<integer> number = Stream.of(1, 2, 3, 4, 5);
List<integer> result2 = number.filter(x -> x!= 3).collect(Collectors.toList());
result2.forEach(x -> System.out.println(x));
}
}
output
1
2
4
5
References
- Java 8 Streams filter examples
- [Java 8 Collectors JavaDoc][]
[Java 8 Collectors JavaDoc]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html