只有在parallel()并行处理情况下,才会有差别。
forEach在并行情况下,自由执行,不考虑顺序。
forEachOrdered在并行情况下,按顺序执行。
代码:
//如果不是parallel()并行处理, 这2个方法没区别
Stream.of("AAA","BBB","CCC").forEach(s->System.out.println("Output:"+s));
Stream.of("AAA","BBB","CCC").forEachOrdered(s->System.out.println("Output:"+s));
//parallel()并行处理的情况下,还想保证顺序,就用forEachOrdered
Stream.of("AAA","BBB","CCC").parallel().forEach(s->System.out.println("Output:"+s));
Stream.of("AAA","BBB","CCC").parallel().forEachOrdered(s->System.out.println("Output:"+s));