|
| 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