Java 8 – 将 Stream 转换为 List

 一个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后将其转换为List(列表)。

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

  1. Java 8 Streams filter examples
  2. Java 8 Collectors JavaDoc
    原文作者:wangmm0218
    原文地址: https://blog.csdn.net/wangmuming/article/details/72750084
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞