The following code works and produces a String that is a result of concatenating first 100 unicode characters starting from 1. [I'm working on 1.8 version of Java]
Stream<Character> chars = Stream.iterate('1', op -> (char)(op + 1));
StringBuilder value = chars.limit(100).reduce
(new StringBuilder(""), (s, c) -> s.append(c), (p,d) -> p.append(d) );
System.out.println(value.toString());
Output of the above is --
123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~?????????????????????
But when I make chars a parallel stream as follows, I get an IndexOutOfBoundsException --
Stream<Character> chars = Stream.iterate('1', op -> (char)(op + 1));
StringBuilder value = chars.parallel().limit(100).reduce
(new StringBuilder(""), (s, c) -> s.append(c), (p,d) -> p.append(d) );
System.out.println(value.toString());
I expected that the order of the characters in the value string would be different since this is a parallel stream but the program would work even for a parallel stream if order did not matter. But I'm getting an IndexOutOfBoundsException. Why am I getting the IndexOutOfBoundsException if make my stream parallel.