|
| 1 | +package com.platzi.functional._04_functional; |
| 2 | + |
| 3 | +import com.platzi.functional.util.Utils; |
| 4 | + |
| 5 | +import java.util.Comparator; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.function.Function; |
| 9 | + |
| 10 | +public class _01_FunctionDemo { |
| 11 | + |
| 12 | + |
| 13 | + /** |
| 14 | + * La interface Function trabaja sobre generics, siendo el primero el tipo de entrada |
| 15 | + * y el segundo el resultado de ejecutar esa funcion. |
| 16 | + */ |
| 17 | + private static <TYPE, RESULT> void metodoDeEjemplo() { |
| 18 | + //Podemos crear instancias bajo demanda… |
| 19 | + Function<TYPE, RESULT> someFun = new Function<TYPE, RESULT>() { |
| 20 | + /** |
| 21 | + * El unico metodo que hay que implementar es el metodo apply. |
| 22 | + * Este metodo tomara el TYPE y debera generar un RESULT |
| 23 | + */ |
| 24 | + @Override |
| 25 | + public RESULT apply(TYPE t) { |
| 26 | + return null; |
| 27 | + } |
| 28 | + }; |
| 29 | + |
| 30 | + //Y luego invocar el metodo apply con parametros del tipo correspondiente… |
| 31 | + someFun.apply(null); |
| 32 | + } |
| 33 | + |
| 34 | + |
| 35 | + /** |
| 36 | + * Veamos un ejemplo simple… una funcion que nos devuelve si un numero es par |
| 37 | + */ |
| 38 | + private static void functionExample() { |
| 39 | + Function<Integer, Boolean> isEven = new Function<Integer, Boolean>() { |
| 40 | + @Override |
| 41 | + public Boolean apply(Integer integer) { |
| 42 | + return integer % 2 == 0; |
| 43 | + } |
| 44 | + }; |
| 45 | + |
| 46 | + isEven.apply(2); // True |
| 47 | + isEven.apply(200); // True |
| 48 | + isEven.apply(18); // True |
| 49 | + |
| 50 | + isEven.apply(25); // False |
| 51 | + isEven.apply(31); // False |
| 52 | + isEven.apply(191); // False |
| 53 | + } |
| 54 | +// |
| 55 | + |
| 56 | + |
| 57 | + // |
| 58 | +// El proceso es muy similar a tener definidos metodos o instancias anonimas como al ordenar numeros. |
| 59 | + private static void sortNumbers(List<Integer> numbers) { |
| 60 | + //Aqui generamos una instancia anonima de comparator |
| 61 | + numbers.sort(new Comparator<Integer>() { |
| 62 | + @Override |
| 63 | + public int compare(Integer o1, Integer o2) { |
| 64 | + return o1 - o2; |
| 65 | + } |
| 66 | + }); |
| 67 | + } |
| 68 | +// |
| 69 | +// |
| 70 | +// |
| 71 | +// |
| 72 | +// |
| 73 | +// |
| 74 | +// |
| 75 | +// |
| 76 | +// |
| 77 | +// |
| 78 | +// |
| 79 | +// |
| 80 | +// |
| 81 | +// |
| 82 | +// |
| 83 | +// |
| 84 | +// |
| 85 | +// |
| 86 | +// |
| 87 | +// |
| 88 | + |
| 89 | + /** |
| 90 | + * Tambien podemos crear clases mas complejas que implementen esta interface… |
| 91 | + */ |
| 92 | + class FunctionBy2 implements Function<Integer, Integer> { |
| 93 | + @Override |
| 94 | + public Integer apply(Integer x) { |
| 95 | + return x * 2; |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Y despues usar esas instancias… |
| 101 | + * hasta ahora nada nuevo o realmente funcional… |
| 102 | + * en realidad esto es solo lo que ya conocemos de usar interfaces y OOP. |
| 103 | + */ |
| 104 | + private static void useBy2(FunctionBy2 by2) { |
| 105 | + int y = by2.apply(5); |
| 106 | + } |
| 107 | + |
| 108 | +// |
| 109 | +// |
| 110 | + |
| 111 | +// |
| 112 | +// |
| 113 | +// |
| 114 | + |
| 115 | +// |
| 116 | +// |
| 117 | +// |
| 118 | +// |
| 119 | +// |
| 120 | +// |
| 121 | +// |
| 122 | +// |
| 123 | +// |
| 124 | +// |
| 125 | +// |
| 126 | +// |
| 127 | +// |
| 128 | +// |
| 129 | + |
| 130 | + /** |
| 131 | + * Lo interesante viene cuando entendemos que una funcion es un tipo… |
| 132 | + * (mantengamonos con funciones y enteros por ahora) |
| 133 | + */ |
| 134 | + private static void functionsAreTypes() { |
| 135 | + /* |
| 136 | + Si una funcion es un tipo, tambien podemos usarla con generics. |
| 137 | + Por ejemplo, devolver una funcion como resultado de ejecutar una funcion… |
| 138 | +
|
| 139 | + Es algo parecido a obtener una sublista de una lista: |
| 140 | + ->> List<X> sub = list.sublist(0, 5); |
| 141 | + */ |
| 142 | + Function<Integer, Function<Integer, Integer>> multiply = |
| 143 | + new Function<Integer, Function<Integer, Integer>>() { |
| 144 | + @Override |
| 145 | + public Function<Integer, Integer> apply(Integer x) { |
| 146 | + //Creamos una nueva funcion y la retornamos |
| 147 | + return new Function<Integer, Integer>() { |
| 148 | + @Override |
| 149 | + public Integer apply(Integer y) { |
| 150 | + return x * y; |
| 151 | + } |
| 152 | + }; |
| 153 | + } |
| 154 | + }; |
| 155 | + |
| 156 | + //Usando nuestra nueva funcion… |
| 157 | + multiply.apply(5).apply(4); // Resultado: 20 |
| 158 | + multiply.apply(15).apply(3); // Resultado: 45 |
| 159 | + multiply.apply(2).apply(4); // Resultado: 8 |
| 160 | + multiply.apply(9).apply(7); // Resultado: 63 |
| 161 | + |
| 162 | + //O podemos crear funciones derivados de la primer funcion: |
| 163 | + Function<Integer, Integer> multiplyBy3 = multiply.apply(3); |
| 164 | + |
| 165 | + multiplyBy3.apply(2); //6 |
| 166 | + multiplyBy3.apply(13); //39 |
| 167 | + multiplyBy3.apply(9); //27 |
| 168 | + } |
| 169 | + |
| 170 | +// |
| 171 | +// |
| 172 | +// |
| 173 | +// |
| 174 | +// |
| 175 | +// |
| 176 | +// |
| 177 | +// |
| 178 | +// |
| 179 | +// |
| 180 | +// |
| 181 | +// |
| 182 | +// |
| 183 | +// |
| 184 | +// |
| 185 | +// |
| 186 | +// |
| 187 | +// |
| 188 | +// |
| 189 | + |
| 190 | + /** |
| 191 | + * Pero la sintaxis de crear instancias de interfaces es demasiado extensa y complicada de leer… |
| 192 | + * usemos la nueva sintaxis de java 8 para funciones |
| 193 | + * (explicaremos todas las sintaxis y las diferencias mas adelante) |
| 194 | + */ |
| 195 | + private static void syntaxFixing() { |
| 196 | + |
| 197 | + Function<Integer, Integer> multiplyBy5 = x -> x * 5; |
| 198 | + |
| 199 | + //Con esto nos ahorramos crear una clase que implemente la interfaz |
| 200 | + //Crear funciones se hace mas simple… |
| 201 | + multiplyBy5.apply(10); //Resulta en: 50 |
| 202 | + |
| 203 | + //Incluso para funciones que retornan funciones (high order functions recuerdas?)… |
| 204 | + Function<Integer, Function<Integer, Integer>> multiplyXByY = |
| 205 | + x -> |
| 206 | + y -> x * y; |
| 207 | + |
| 208 | + //Sabemos que al mandar a llamar al metodo apply obtendremos una nueva funcion… |
| 209 | + Function<Integer, Integer> multiply2ByY = multiplyXByY.apply(2); |
| 210 | + |
| 211 | + multiply2ByY.apply(7); // Nos resultara en 14 |
| 212 | + |
| 213 | + //O podemos seguir llamando al resultado directamente |
| 214 | + multiplyXByY.apply(9).apply(8); //72 |
| 215 | + } |
| 216 | + |
| 217 | +// |
| 218 | +// |
| 219 | +// |
| 220 | +// |
| 221 | +// |
| 222 | +// |
| 223 | +// |
| 224 | +// |
| 225 | +// |
| 226 | +// |
| 227 | +// |
| 228 | +// |
| 229 | +// |
| 230 | +// |
| 231 | + |
| 232 | +// |
| 233 | +// |
| 234 | +// |
| 235 | +// |
| 236 | +// |
| 237 | +// |
| 238 | +// |
| 239 | +// |
| 240 | + |
| 241 | + /** |
| 242 | + * Lo bueno empieza no cuando las definimos… |
| 243 | + * empieza cuando las empezamos a pasar como parametros y recibir como resultados… |
| 244 | + */ |
| 245 | + private static void funWithFuns() { |
| 246 | + List<Integer> myNumbers = Utils.getListOf(1, 2, 3, 4, 5, 6); |
| 247 | + |
| 248 | + //Funcion que eleva un numero al cuadrado |
| 249 | + Function<Integer, Integer> square = x -> x * x; |
| 250 | + |
| 251 | + //Funcion que eleva un numero al cubo |
| 252 | + Function<Integer, Integer> cube = x -> x * x * x; |
| 253 | + |
| 254 | + //Funcion que convierte un entero en negativo |
| 255 | + Function<Integer, Integer> toNegative = x -> -1 * x; |
| 256 | + |
| 257 | + applyMathToList(myNumbers, square); // [1, 4, 9, 16, 25, 36] |
| 258 | + applyMathToList(myNumbers, cube); // [1, 8, 27, 64, 125, 216] |
| 259 | + applyMathToList(myNumbers, toNegative); // [-1, -2, -3, -4, -5, -6] |
| 260 | + } |
| 261 | + |
| 262 | +// |
| 263 | +// |
| 264 | +// |
| 265 | + |
| 266 | + /** |
| 267 | + * Podemos decir que algunos metodos son funciones, en este caso, este metodo es una |
| 268 | + * funcion de orden mayor que toma como parametro otra funcion y la usa para operar |
| 269 | + * sobre la lista. |
| 270 | + */ |
| 271 | + private static List<Integer> applyMathToList( |
| 272 | + List<Integer> items, |
| 273 | + Function<Integer, Integer> operation |
| 274 | + ) { |
| 275 | + List<Integer> resultItems = new LinkedList<>(); |
| 276 | + for (Integer x : items) { |
| 277 | + resultItems.add(operation.apply(x)); |
| 278 | + } |
| 279 | + return resultItems; |
| 280 | + } |
| 281 | + |
| 282 | + |
| 283 | +// |
| 284 | +// |
| 285 | +// |
| 286 | +// |
| 287 | +// |
| 288 | +// |
| 289 | +// |
| 290 | +// |
| 291 | +// |
| 292 | +// |
| 293 | +// |
| 294 | +// |
| 295 | +// |
| 296 | +// |
| 297 | +// |
| 298 | +// |
| 299 | +// |
| 300 | + |
| 301 | + /** |
| 302 | + * Incluso podriamos hacer cosas mas interesantes como aplicar muchas funciones sobre un dato |
| 303 | + */ |
| 304 | + private static String transformText(String text) { |
| 305 | + List<Function<String, String>> transformations = new LinkedList<>(); |
| 306 | + |
| 307 | + transformations.add(s -> s.toUpperCase()); |
| 308 | + transformations.add(s -> s.replaceAll("SI", "TI")); |
| 309 | + transformations.add(s -> s.replaceAll("RO", "YO")); |
| 310 | + transformations.add(s -> s.replaceAll("O", "OoO")); |
| 311 | + |
| 312 | + String result = text; |
| 313 | + for (Function<String, String> function : transformations) { |
| 314 | + result = function.apply(result); |
| 315 | + } |
| 316 | + return result; |
| 317 | + } |
| 318 | + |
| 319 | + |
| 320 | + private static void runTransform() { |
| 321 | + System.out.println(transformText("Hello")); //HELLOoO |
| 322 | + System.out.println(transformText("World")); //WOoORLD |
| 323 | + System.out.println(transformText("Claro que si roncas")); //CLAYOoO QUE TI YOoONCAS |
| 324 | + } |
| 325 | + |
| 326 | + public static void main(String[] args) { |
| 327 | + runTransform(); |
| 328 | + } |
| 329 | +} |
0 commit comments