我很难理解为什么并行流和流对于完全相同的语句给出不同的结果。

    List<String> list = Arrays.asList("1", "2", "3");
    String resultParallel = list.parallelStream().collect(StringBuilder::new,
            (response, element) -> response.append(" ").append(element),
            (response1, response2) -> response1.append(",").append(response2.toString()))
            .toString();
    System.out.println("ResultParallel: " + resultParallel);

    String result = list.stream().collect(StringBuilder::new,
            (response, element) -> response.append(" ").append(element),
            (response1, response2) -> response1.append(",").append(response2.toString()))
            .toString();

    System.out.println("Result: " + result);

结果平行:1,2,3

结果:1 2 3

有人可以解释为什么会这样,以及我如何获得非并行版本以提供与并行版本相同的结果吗?

最佳答案

附带说明一下,即使您用,中的空格替换combiner,您的结果仍然会有所不同(略微更改了代码以使其更具可读性):

String resultParallel = list.parallelStream().collect(
            StringBuilder::new,
            (builder, elem) -> builder.append(" ").append(elem),
            (left, right) -> left.append(" ").append(right)).toString();

    String result = list.stream().collect(
            StringBuilder::new,
            (builder, elem) -> builder.append(" ").append(elem),
            (left, right) -> left.append(" ").append(right)).toString();


  System.out.println("ResultParallel: ->" + resultParallel + "<-"); // -> 1  2  3  4<-
  System.out.println("Result: ->" + result + "<-"); // -> 1 2 3 4<-

请注意您的空间太多了。

Java文档具有提示:



如果要加入,有一些更简单的选项,例如:
String.join(",", yourList)
yourList.stream().collect(Collectors.joining(","))

关于java - 并行流的行为与流不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51724266/

10-15 23:42