2017-08-30 14 views
7

Jestem nowicjuszem w języku Java 8. Uczę się metody strumieniowej API reduce. Widzę dziwne zachowanie z tym kodem:Dlaczego funkcja łączenia sumatora nie jest wykonywana?

public class PrdefinedCollectors { 
    public static void main(String[] args) { 
     Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6); 
     List<Integer> dataHolder = new ArrayList<Integer>(); 
     List<Integer> numbers = stream.reduce(dataHolder, 
      (List<Integer> dataStore, Integer data) -> { 
        System.out.println(data + " ->: " + dataStore); 
        dataStore.add(data); 
        return dataStore; 
       }, 
      (List<Integer> listOne, List<Integer> listTwo) -> { 
        System.out.println("ListOne Data :" + listOne + " List Two data :" + listTwo); 
        listOne.addAll(listTwo); 
        return listOne; 
       }); 

     System.out.println(numbers); 
    } 
} 

wyjściowa:

1 ->: [] 
2 ->: [1] 
3 ->: [1, 2] 
4 ->: [1, 2, 3] 
5 ->: [1, 2, 3, 4] 
6 ->: [1, 2, 3, 4, 5] 
[1, 2, 3, 4, 5, 6] 

Moje pytanie brzmi, dlaczego funkcja sumator nie wykonując czyli dlaczego ten wiersz:

System.out.println("List One Data: " + listOne + " List Two data: " + listTwo); 

.. . nie jest wykonany?

Odpowiedz

9

Dzieje się tak, ponieważ nie używasz parallelStream().

A combiner jest tylko wymagane do równoległego strumienia.

Ale to nie jest jedyny problem w kodzie, reduce jest przypuszczać, aby pracować z niezmiennej danych - kodu, sposób, w jaki jest teraz, nie powiedzie się do równoległego strumienia. Ten byłoby praca dla collect, ale dla reduce trzeba go zmienić na:

List<Integer> numbers = stream 
      .parallel() 
      .reduce(
        new ArrayList<>(), 
        (list, data) -> { 
         ArrayList<Integer> newList = new ArrayList<>(list); 
         newList.add(data); 
         return newList; 
        }, 

        (left, right) -> { 
         ArrayList<Integer> newList = new ArrayList<>(left); 
         newList.addAll(right); 
         return newList; 
        }); 
+0

Dzięki got it !. – vicky

+2

Poprawiono nieco odpowiedź, aby było bardziej zrozumiałe. Wiesz, jak to zrobić, jeśli nie spodobają mi się moje zmiany. – GhostCat

Powiązane problemy