Streamline intermediate flow operations

Is there a guarantee that when working with a stream, intermediate operations will be performed in the order of the program execution? I suspect this is so, or it will lead to very subtle errors, but I could not find a definite answer.

Example:

List<String> list = Arrays.asList("a", "b", "c");
List<String> modified = list.parallelStream()
        .map(s -> s + "-" + s)                 //"a-a", "b-b", "c-c"
        .filter(s -> !s.equals("b-b"))         //"a-a", "c-c"
        .map(s -> s.substring(2))              //"a", "c"
        .collect(toList());

Is always guaranteed a refund ["a", "c"]or ["c", "a"]? (if the last card operation is performed before the first card operation, which may cause an exception - similarly, if the filter is performed after the second card operation, “b” will be saved in the final list)

+4
source share
2 answers

- , . , , :

  • Stream<A> B, Stream<B>
  • Filter<B>
  • Stream<B> C, Stream<C>
  • C List<C>

, , - .

, String Stream. , , , .

Stream , , . sorted distinct , , ​​Comparator. , .

+6

, .

Holger . , , , , - . , , ,

List<String> modified = list.parallelStream()
    .filter(s -> !s.equals("b-b")) // these two operations are swapped
    .map(s -> s + "-" + s)         // compared to the original example
    .map(s -> s.substring(2))
    .collect(toList());

[a, b, c]. .

, [c, a] [a, c]. , . java.util.stream. , , . , ( ) - .

, , HashSet ArrayList. , HashSet, , , . HashSet, , , , , , .

, List, . [a, b, c], , , "a" "b", "c". .

, . , , :

List<String> list = Arrays.asList("c", "b", "a");
List<String> modified = list.parallelStream()
    .map(s -> s + "-" + s)                 //"c-c", "b-b", "a-a"
    .filter(s -> !s.equals("b-b"))         //"c-c", "a-a"
    .map(s -> s.substring(2))              //"c", "a"
    .collect(toList());

, [c, a]. :

List<String> list = Arrays.asList("c", "b", "a");
Set<String> set = new HashSet<>(list);
List<String> modified = set.parallelStream()
    .map(s -> s + "-" + s)
    .filter(s -> !s.equals("b-b"))
    .map(s -> s.substring(2))
    .collect(toList());

[a, c]. (, , ) , undefined, , .

( , , HashSet - , -.)

"", . . , . ( , , , , , , .) :

List<Integer> list1 = Collections.synchronizedList(new ArrayList<>());
List<Integer> list2 =
    IntStream.range(0, 10)
        .parallel()
        .boxed()
        .peek(i -> list1.add(i))
        .collect(toList());
System.out.println(list1);
System.out.println(list2);

:

[5, 6, 2, 3, 4, 8, 9, 7, 0, 1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2, 1 . list1 run run, list2 .

, :

  • ;
  • .

.

+9

Source: https://habr.com/ru/post/1529007/


All Articles