一个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);
}
}
输出
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));
}
}
输出
1
2
4
5
参考文献
翻译自: https://mkyong.com/java8/java-8-convert-a-stream-to-list/