Skip to content

Commit bdba81f

Browse files
committed
Operaciones finales con ejemplos
1 parent 27fec99 commit bdba81f

3 files changed

Lines changed: 138 additions & 2 deletions

File tree

modules/src/main/java/com/platzi/functional/_17_operators_collectors/Operators.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ o convertir todos los datos de un Stream a un tipo en concreto (por ejemplo, con
140140
//
141141
//
142142
//
143-
static Stream<List<String>> getCourses() {
143+
public static Stream<List<String>> getCourses() {
144144
List<String> nodeCourses = Utils.getListOf("Node.js:Intermedio", "Express.js:Intermedio", "Eventloop:Avanzado");
145145
List<String> javaCourses = Utils.getListOf("Spring:Introductorio", "Maven:Intermedio", "Gradle:Avanzado", "Funtional:Introductorio");
146146

modules/src/main/java/com/platzi/functional/_18_intermediate_ops/IntermediateOperations.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class IntermediateOperations {
1010
static void operaciones() {
1111
/*
1212
Las operaciones intermedias, como se vio en el modulo anterior, son operaciones que
13-
devuelven un nuevo Stream.
13+
retornan un nuevo Stream.
1414
1515
Estas operaciones son:
1616
@@ -91,5 +91,11 @@ Es una manera sencilla de hacer una operacion intermedia sobre el Stream sin alt
9191
*/
9292
Stream<String> choosenTwoHeroes = justTwoHeroes.peek(heroe -> System.out.println("Un heroe ha sido elegido: " + heroe));
9393

94+
/*
95+
Existen otras operaciones como sorted() que alteran el orden del Stream
96+
o mas especificas como las operaciones mapTo… que convierten el Stream de un tipo a otro
97+
98+
Es importante entender que estas operaciones solo generan nuevos Stream con cada invocacion.
99+
*/
94100
}
95101
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package com.platzi.functional._19_final_ops;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
import java.util.stream.Collectors;
6+
import java.util.stream.Stream;
7+
8+
import static com.platzi.functional._17_operators_collectors.Operators.getCourses;
9+
10+
public class FinalOperations {
11+
static void operaciones() {
12+
/*
13+
Las Operaciones finales son, como se menciono antes, las operaciones que generan un valor
14+
final despues de iterar los elementos del stream.
15+
16+
Dichas operaciones son:
17+
- anyMatch()
18+
- allMatch()
19+
- noneMatch()
20+
- collect()
21+
- count()
22+
- findAny()
23+
- findFirst()
24+
- forEach()
25+
- min()
26+
- max()
27+
- reduce()
28+
- toArray()
29+
*/
30+
31+
//anyMatch
32+
//Nos indica si un stream contiene un elemento segun el Predicate que le pasemos:
33+
Stream<Integer> numbersStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 11);
34+
boolean biggerThanTen = numbersStream.anyMatch(i -> i > 10); //true porque tenemos el 11
35+
36+
//allMatch
37+
//Nos indica si todos los elementos de un Stream cumplen con un cierto Predicate:
38+
Stream<Integer> agesStream = Stream.of(19, 21, 35, 45, 12);
39+
boolean allLegalDrinkingAge = agesStream.allMatch(age -> age > 18); //false, tenemos un menor
40+
41+
//noneMatch
42+
//Nos indica si todos los elementos de un Stream NO CUMPLEN un cierto Predicate:
43+
Stream<Integer> oddNumbers = Stream.of(1, 3, 5, 7, 9, 11);
44+
boolean allAreOdd = oddNumbers.noneMatch(i -> i % 2 == 0);
45+
46+
//collect
47+
//Recibe un Collector para juntar todos los elementos del Stream en un cierto tipo:
48+
Stream<String> studentsStream = Stream.of("Tu", "Yo");
49+
List<String> studentsList = studentsStream.collect(Collectors.toList());
50+
51+
//count
52+
//Nos indica cuantos elementos tiene un Stream
53+
Stream<Integer> yearsStream = Stream.of(1990, 1991, 1994, 2000, 2010, 2019, 2020);
54+
long yearsCount = yearsStream.count(); //7, solo nos dice cuantos datos tuvo el stream.
55+
56+
57+
//findAny
58+
/*
59+
Nos retorna un Optional con un elemento, cualquiera del Stream, o Optional.empty()
60+
si no hay elementos en el Stream. Esta operacion puede devolver cualquier elemento
61+
del Stream.
62+
*/
63+
Stream<List<String>> coursesStream = getCourses();
64+
Optional<List<String>> coursesOptional = coursesStream.findAny();
65+
66+
//findFirst
67+
//Retorna un Optional con el primer elemento del Stream o Optional.empty() si no hay elementos en el Stream
68+
Stream<List<String>> availableCourses = getCourses();
69+
Optional<List<String>> firstCoursesOptional = coursesStream.findFirst();
70+
71+
72+
//forEach
73+
//Itera cada elemento del Stream pasandolo al Consumer que se da como parametro:
74+
Stream<List<String>> courses = getCourses();
75+
courses.forEach(courseList -> System.out.println("Cursos disponibles: " + courseList));
76+
77+
//min
78+
//Nos retorna un Optioanl con el elemento con valor minimo del Stream usando un Comparator para encontrarlo
79+
// o Optional.empty() si el Stream no tenia elementos
80+
Stream<Long> bigNumbers = Stream.of(100L, 200L, 1000L, 5L);
81+
Optional<Long> minimumOptional = bigNumbers.min((numberX, numberY) -> (int) Math.min(numberX, numberY));
82+
83+
//max
84+
//Escencialmente lo mismo que Stream.min, solo que retornando un Optional con el valor MAXIMO:
85+
Stream<Long> bigNumbersAgain = Stream.of(100L, 200L, 1000L, 5L);
86+
Optional<Long> maximumOptional = bigNumbers.min((numberX, numberY) -> (int) Math.max(numberX, numberY));
87+
88+
//reduce
89+
/*
90+
Existe en tres formas:
91+
reduce(valorInicial, BinaryOperator)
92+
reduce(BinaryAccumulator)
93+
reduce(valorInicial, BinaryFunction, BinaryOperator)
94+
95+
La diferencia entre los 3 tipos de invocacion:
96+
97+
- reduce(BinaryAccumulator)
98+
retorna un Optional del mismo tipo que el Stream, con un solo valor resultante de aplicar
99+
el BinaryAccumulator sobre cada elemento O Optional.empty() si el stream estaba vacio.
100+
Puede generar un NullPointerException en casos donde el resultado de BinaryAccumulator sea null
101+
102+
- reduce(valorInicial, BinaryOperator)
103+
retorna un valor del mismo tipo que el Stream, despues de aplicar BinaryOperator sobre cada
104+
elemento del Stream, en caso de un Stream vacio, el valorInicial es retornado.
105+
106+
Y el caso mas interesante…
107+
108+
- reduce(valorInicial, BinaryFunction<V, T, V>, BinaryOperator<V>)
109+
Genera un valor de tipo V, despues de aplicar BinaryFunction sobre cada elemento de tipo T en el Stream
110+
y obtener un resultado V. Esta version de reduce usa el BinaryFunction como map + reduce. Es decir
111+
por cada elemento en el Stream, se genera un valor V basado en el valorInical y el resultado anterior de
112+
la BinaryFunction. BinaryOperator se utiliza en streams paralelos (stream.parallel()) para determinar el
113+
valor que se debe mantener en cada iteracion.
114+
115+
*/
116+
117+
//reduce(BinaryAccumulator)
118+
Stream<String> aLongStoryStream = Stream.of("Cuando", "despertó,", "el", "dinosaurio", "todavía", "estaba", "allí.");
119+
Optional<String> longStoryOptional = aLongStoryStream.reduce((previousStory, nextPart) -> previousStory + " " + nextPart);
120+
longStoryOptional.ifPresent(System.out::println); //"Cuando despertó, el dinosaurio todavía estaba allí."
121+
122+
//reduce(valorInicial, BinaryOperator)
123+
Stream<Integer> firstTenNumbersStream = Stream.iterate(0, i -> i + 1).limit(10);
124+
int sumOfFirstTen = firstTenNumbersStream.reduce(0, Integer::sum); //45 -> 0 + 1 + … + 9
125+
126+
//reduce(valorInicial, BinaryFunction<V, T, V> acumulador, BinaryOperator<V> combinador)
127+
Stream<String> aLongStoryStreamAgain = Stream.of("Cuando", "despertó,", "el", "dinosaurio", "todavía", "estaba", "allí.");
128+
int charCount = aLongStoryStreamAgain.reduce(0, (count, word) -> count + word.length(), Integer::sum);
129+
}
130+
}

0 commit comments

Comments
 (0)