定义:支持顺序和并行聚合操作的元素序列
Stream流本身并不储存数据
Stream流属于管道流,仅可使用一次;二次使用会抛出IllegalStateException: stream has already been operated upon or closed异常
需要注意的是,parallelStream方法的源码注释中提到,该方法返回的不一定是并行流,也就是说任务可能均由调用者线程执行
- * @return a possibly parallel {@code Stream} over the elements in this
- * collection
- * @since 1.8
parallelStream方法返回并行流示例:
- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.parallelStream().forEach((num) -> {
- System.out.println(Thread.currentThread().getName() + " num=" + num);
- });
- }
- }
若想将流中的数据依次输出,可使用forEachOrdered方法:

注:若直接调用forEach方法,则调用的是Iterable接口中的forEach方法
- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.stream().forEach(System.out::println);
- }
- }
- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.stream().limit(3).forEach(System.out::println);
- }
- }

- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.stream().filter(num -> num>=3).forEach(System.out::println);
- }
- }

- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.stream().map(num -> num+1).forEach(System.out::println);
- }
- }

- public class Test {
- public static void main(String[] args){
- List
list = Arrays.asList(1, 2, 3, 4, 5); -
- list.stream().sorted().forEach(System.out::print);
- System.out.println();
- list.stream().sorted(Integer::compareTo).forEach(System.out::print);
- System.out.println();
- list.stream().sorted((num1, num2) -> num2 - num1).forEach(System.out::print);
- }
- }
