|
| 1 | + |
| 2 | +# JAVA 8 - Chuleta |
| 3 | + |
| 4 | +## Expresión Lambda |
| 5 | +```java |
| 6 | +(int a) -> a * 2; // Calcula el docble de a |
| 7 | +a -> a * 2; // o simplemente sin tipo |
| 8 | +``` |
| 9 | +```java |
| 10 | +(a, b) -> a + b; // Suma 2 parametros |
| 11 | +``` |
| 12 | + |
| 13 | +Si lambda tiene mas de una expresión podemos usar `{ }` y `return` |
| 14 | + |
| 15 | +```java |
| 16 | +(x, y) -> { |
| 17 | +int sum = x + y; |
| 18 | +int avg = sum / 2; |
| 19 | +return avg; |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +Una expresión lambda no puede usarse sola en Java, necesita estar asociada a un interfaz funcional |
| 24 | + |
| 25 | +```java |
| 26 | +interface MyMath { |
| 27 | + int getDoubleOf(int a); |
| 28 | +} |
| 29 | + |
| 30 | +MyMath d = a -> a * 2; // asociado a un interfaz |
| 31 | +d.getDoubleOf(4); // es 8 |
| 32 | +``` |
| 33 | + |
| 34 | +--- |
| 35 | + |
| 36 | +Todos los ejemplos con "list" usan: |
| 37 | + |
| 38 | +```java |
| 39 | +List<String> list = [Bohr, Darwin, Galilei, Tesla, Einstein, Newton] |
| 40 | +``` |
| 41 | + |
| 42 | + |
| 43 | +## Colecciones |
| 44 | + |
| 45 | +**sort** `sort(list, comparator)` |
| 46 | + |
| 47 | +```java |
| 48 | +list.sort((a, b) -> a.length() - b.length()) |
| 49 | +list.sort(Comparator.comparing(n -> n.length())); // igual |
| 50 | +list.sort(Comparator.comparing(String::length)); // igual |
| 51 | +//> [Bohr, Tesla, Darwin, Newton, Galilei, Einstein] |
| 52 | +``` |
| 53 | + |
| 54 | +**removeIf** |
| 55 | + |
| 56 | +```java |
| 57 | +list.removeIf(w -> w.length() < 6); |
| 58 | +//> [Darwin, Galilei, Einstein, Newton] |
| 59 | +``` |
| 60 | + |
| 61 | +**merge** |
| 62 | +`merge(key, value, remappingFunction)` |
| 63 | + |
| 64 | +```java |
| 65 | +Map<String, String> names = new HashMap<>(); |
| 66 | +names.put("Albert", "Ein?"); |
| 67 | +names.put("Marie", "Curie"); |
| 68 | +names.put("Max", "Plank"); |
| 69 | + |
| 70 | +// El valor "Albert" existe |
| 71 | +// {Marie=Curie, Max=Plank, Albert=Einstein} |
| 72 | +names.merge("Albert", "stein", (old, val) -> old.substring(0, 3) + val); |
| 73 | + |
| 74 | +// El valor "Newname" no existe |
| 75 | +// {Marie=Curie, Newname=stein, Max=Plank, Albert=Einstein} |
| 76 | +names.merge("Newname", "stein", (old, val) -> old.substring(0, 3) + val); |
| 77 | +``` |
| 78 | + |
| 79 | + |
| 80 | +## Expresión de metodo `Class::staticMethod` |
| 81 | + |
| 82 | +Permite referenciar métodos (y constructores) sin ejecutarlos |
| 83 | + |
| 84 | +```java |
| 85 | +// Con Lambda: |
| 86 | +getPrimes(numbers, a -> StaticMethod.isPrime(a)); |
| 87 | + |
| 88 | +// Metodo Referenciado: |
| 89 | +getPrimes(numbers, StaticMethod::isPrime); |
| 90 | +``` |
| 91 | + |
| 92 | +| Método Referenciado | Forma de Lambda | |
| 93 | +| ------------------- | --------------- | |
| 94 | +| `StaticMethod::isPrime` | `n -> StaticMethod.isPrime(n)` | |
| 95 | +| `String::toUpperCase` | `(String w) -> w.toUpperCase()` | |
| 96 | +| `String::compareTo` | `(String s, String t) -> s.compareTo(t)` | |
| 97 | +| `System.out::println` | `x -> System.out.println(x)` | |
| 98 | +| `Double::new` | `n -> new Double(n)` | |
| 99 | +| `String[]::new` | `(int n) -> new String[n]` | |
| 100 | + |
| 101 | + |
| 102 | +## Streams |
| 103 | + |
| 104 | +Similares a las colecciones, pero: |
| 105 | + |
| 106 | + - No almacenan su propia información |
| 107 | + - La información viene de otra parte (colleciones, archivos, db, web, ...) |
| 108 | + - *immutable* (crean un nuevo stream) |
| 109 | + - *lazy* (solo computa lo que es necesario !) |
| 110 | + |
| 111 | +```java |
| 112 | +// Computara 3 "filter" |
| 113 | +Stream<String> longNames = list |
| 114 | + .filter(n -> n.length() > 8) |
| 115 | + .limit(3); |
| 116 | +``` |
| 117 | + |
| 118 | +**Crea un nuevo stream** |
| 119 | + |
| 120 | +```java |
| 121 | +Stream<Integer> stream = Stream.of(1, 2, 3, 5, 7, 11); |
| 122 | +Stream<String> stream = Stream.of("Jazz", "Blues", "Rock"); |
| 123 | +Stream<String> stream = Stream.of(myArray); // or from an array |
| 124 | +list.stream(); // or from a list |
| 125 | + |
| 126 | +// Stream infinito [0; inf[ |
| 127 | +Stream<Integer> integers = Stream.iterate(0, n -> n + 1); |
| 128 | +``` |
| 129 | + |
| 130 | +**Resultado de las colecciones** |
| 131 | + |
| 132 | +```java |
| 133 | +// Collect into an array (::new is the constructor reference) |
| 134 | +// Colecciona en un array (::new es la referencia del contructor) |
| 135 | +String[] myArray = stream.toArray(String[]::new); |
| 136 | + |
| 137 | +// Collecciona en un List o Set |
| 138 | +List<String> myList = stream.collect(Collectors.toList()); |
| 139 | +Set<String> mySet = stream.collect(Collectors.toSet()); |
| 140 | + |
| 141 | +// Collecciona en un String |
| 142 | +String str = list.collect(Collectors.joining(", ")); |
| 143 | +``` |
| 144 | + |
| 145 | +**map** `map(mapper)`<br> |
| 146 | +Aplica una función a cada elemento |
| 147 | + |
| 148 | +```java |
| 149 | +// Aplica "toLowerCase" a cada elemento |
| 150 | +res = stream.map(w -> w.toLowerCase()); |
| 151 | +res = stream.map(String::toLowerCase); |
| 152 | +//> bohr darwin galilei tesla einstein newton |
| 153 | + |
| 154 | +res = Stream.of(1,2,3,4,5).map(x -> x + 1); |
| 155 | +//> 2 3 4 5 6 |
| 156 | +``` |
| 157 | + |
| 158 | +**filter** `filter(predicado)`<br> |
| 159 | +Retiene elementos que coinciden con el predicado |
| 160 | + |
| 161 | +```java |
| 162 | +// Filtra elementos que empiecen con "E" |
| 163 | +res = stream.filter(n -> n.substring(0, 1).equals("E")); |
| 164 | +//> Einstein |
| 165 | + |
| 166 | +res = Stream.of(1,2,3,4,5).filter(x -> x < 3); |
| 167 | +//> 1 2 |
| 168 | +``` |
| 169 | + |
| 170 | +**reduce**<br> |
| 171 | +Reduce los elementos a un unico valor |
| 172 | + |
| 173 | +```java |
| 174 | +String reduced = stream |
| 175 | +.reduce("", (acc, el) -> acc + "|" + el); |
| 176 | +//> |Bohr|Darwin|Galilei|Tesla|Einstein|Newton |
| 177 | +``` |
| 178 | + |
| 179 | +**limit** `limit(maxSize)` |
| 180 | +Los n primeros elementos |
| 181 | + |
| 182 | +```java |
| 183 | +res = stream.limit(3); |
| 184 | +//> Bohr Darwin Galilei |
| 185 | +``` |
| 186 | + |
| 187 | +**skip** |
| 188 | +Descarta los primeros n elementos |
| 189 | + |
| 190 | +```java |
| 191 | +res = strem.skip(2); // skip Bohr and Darwin |
| 192 | +//> Galilei Tesla Einstein Newton |
| 193 | +``` |
| 194 | + |
| 195 | +**distinct** |
| 196 | +Borra los elementos repetidos |
| 197 | + |
| 198 | +```java |
| 199 | +res = Stream.of(1,0,0,1,0,1).distinct(); |
| 200 | +//> 1 0 |
| 201 | +``` |
| 202 | + |
| 203 | +**sorted** |
| 204 | +Ordena elementos (debe ser *Comparable*) |
| 205 | + |
| 206 | +```java |
| 207 | +res = stream.sorted(); |
| 208 | +//> Bohr Darwin Einstein Galilei Newton Tesla |
| 209 | +``` |
| 210 | + |
| 211 | +**allMatch** |
| 212 | + |
| 213 | +```java |
| 214 | +// Comprueba si hay una "e" en cada elemento |
| 215 | +boolean res = words.allMatch(n -> n.contains("e")); |
| 216 | +``` |
| 217 | + |
| 218 | +anyMatch: Comprueba si hay una "e" en algun elemento<br> |
| 219 | +noneMatch: Comprueba si no hay una "e" en ningun elemento |
| 220 | + |
| 221 | +**parallel** |
| 222 | +Devuelve un stream equivalente que es paralelo |
| 223 | + |
| 224 | +**findAny** |
| 225 | +Mas rapido que findFirst en un stream paralelo |
| 226 | + |
| 227 | +### Streams de tipo primitivo |
| 228 | + |
| 229 | +Los wrappers (como Stream<Integer>) son ineficientes. Requieren de embalar y desembalar cada elemento demasiado. Mejor usar `IntStream`, `DoubleStream`, etc. |
| 230 | + |
| 231 | +**Creacion** |
| 232 | + |
| 233 | +```java |
| 234 | +IntStream stream = IntStream.of(1, 2, 3, 5, 7); |
| 235 | +stream = IntStream.of(myArray); // de un array |
| 236 | +stream = IntStream.range(5, 80); // rango de 5 a 80 |
| 237 | + |
| 238 | +Random gen = new Random(); |
| 239 | +IntStream rand = gen(1, 9); // stream de aleatorios |
| 240 | +``` |
| 241 | + |
| 242 | +Usa *mapToX* (mapToObj, mapToDouble, etc.) si la función produce un valor Object, double, etc. |
| 243 | + |
| 244 | +### Resultados agrupados |
| 245 | + |
| 246 | +**Collectors.groupingBy** |
| 247 | + |
| 248 | +```java |
| 249 | +// Agrupados por longitud |
| 250 | +Map<Integer, List<String>> groups = stream |
| 251 | +.collect(Collectors.groupingBy(w -> w.length())); |
| 252 | +//> 4=[Bohr], 5=[Tesla], 6=[Darwin, Newton], ... |
| 253 | +``` |
| 254 | + |
| 255 | +**Collectors.toSet** |
| 256 | + |
| 257 | +```java |
| 258 | +// Igual que antes pero en un Set |
| 259 | +... Collectors.groupingBy( |
| 260 | +w -> w.substring(0, 1), Collectors.toSet()) ... |
| 261 | +``` |
| 262 | + |
| 263 | +**Collectors.counting** |
| 264 | +Cuenta el numero de elementos en una coleccion |
| 265 | + |
| 266 | +**Collectors.summing__** |
| 267 | +`summingInt`, `summingLong`, `summingDouble` para sumar valores de un grupo |
| 268 | + |
| 269 | +**Collectors.averaging__** |
| 270 | +`averagingInt`, `averagingLong`, ... |
| 271 | + |
| 272 | +```java |
| 273 | +// Longitud promedio de cada elemento de un grupo |
| 274 | +Collectors.averagingInt(String::length) |
| 275 | +``` |
| 276 | + |
| 277 | +*PS*: No olvides Optional (como `Map<T, Optional<T>>`) con algunos metodos de Colecciones (like `Collectors.maxBy`). |
| 278 | + |
| 279 | + |
| 280 | +### Streams Paralelos |
| 281 | + |
| 282 | +**Creacion** |
| 283 | + |
| 284 | +```java |
| 285 | +Stream<String> parStream = list.parallelStream(); |
| 286 | +Stream<String> parStream = Stream.of(myArray).parallel(); |
| 287 | +``` |
| 288 | + |
| 289 | +**unordered** |
| 290 | +Pueden acelerar el `limit` o `distinct` |
| 291 | + |
| 292 | +```java |
| 293 | +stream.parallelStream().unordered().distinct(); |
| 294 | +``` |
| 295 | + |
| 296 | + |
| 297 | +*PS*: Trabaja con la librería de streams. Pe: usa `filter(x -> x.length() < 9)` en vez de `forEach` con un`if`. |
| 298 | + |
| 299 | +## Optional |
| 300 | +En Java, es común usar null para denotar ausencia de resultado. |
| 301 | +Problemas cuando no se comprueban: `NullPointerException`. |
| 302 | + |
| 303 | +```java |
| 304 | +// Optional<String> contiene un string o nada |
| 305 | +Optional<String> res = stream |
| 306 | + .filter(w -> w.length() > 10) |
| 307 | + .findFirst(); |
| 308 | + |
| 309 | +// longitud de res o "", si no trae nada |
| 310 | +int length = res.orElse("").length(); |
| 311 | + |
| 312 | +// lanza el lambda si no trae nada |
| 313 | +res.ifPresent(v -> results.add(v)); |
| 314 | +``` |
| 315 | + |
| 316 | +Devuelve un Optional |
| 317 | + |
| 318 | +```java |
| 319 | +Optional<Double> squareRoot(double x) { |
| 320 | + if (x >= 0) { return Optional.of(Math.sqrt(x)); } |
| 321 | + else { return Optional.empty(); } |
| 322 | +} |
| 323 | +``` |
| 324 | + |
| 325 | +--- |
| 326 | + |
| 327 | +**Note en la inferencia de la limitación** |
| 328 | + |
| 329 | +```java |
| 330 | +interface Pair<A, B> { |
| 331 | + A first(); |
| 332 | + B second(); |
| 333 | +} |
| 334 | +``` |
| 335 | + |
| 336 | +Un stream de tipo `Stream<Pair<String, Long>>` : |
| 337 | + |
| 338 | + - `stream.sorted(Comparator.comparing(Pair::first)) // vale` |
| 339 | + - `stream.sorted(Comparator.comparing(Pair::first).thenComparing(Pair::second)) // no funciona` |
| 340 | + |
| 341 | +Java no puede inferir el tipo para la parte de `.comparing(Pair::first)`y devolver el Objeto, por lo que `Pair::first` no podría ser aplicado. |
| 342 | + |
| 343 | +El tipo requerido para toda la expresión no puede ser propagada a través de la llamada del método (`.thenComparing`) y ser usada para inferir el tipo de la primera parte. |
| 344 | + |
| 345 | +El tipo *debe* ser dado explicitamente |
| 346 | + |
| 347 | +```java |
| 348 | +stream.sorted( |
| 349 | + Comparator.<Pair<String, Long>, String>comparing(Pair::first) |
| 350 | + .thenComparing(Pair::second) |
| 351 | +) // ok |
| 352 | +``` |
| 353 | + |
| 354 | +--- |
| 355 | + |
| 356 | +Esta cheat sheet esta basada en la lección de Cay Horstmann |
| 357 | +http://horstmann.com/heig-vd/spring2015/poo/ |
0 commit comments