Created
November 13, 2025 05:53
-
-
Save alonsoir/b571303a70b544b9c8641a5fcd7a9fc5 to your computer and use it in GitHub Desktop.
La controversia entre ambos estilos (el clásico imperativo y el funcional con Streams) no es tanto de eficiencia como de legibilidad, semántica y filosofía de diseño.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### Version1 | |
| ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); | |
| List<Callable<List<String>>> tareas = new ArrayList<>(); | |
| int chunkSize = usuarios.size() / Runtime.getRuntime().availableProcessors(); | |
| for (int i = 0; i < usuarios.size(); i += chunkSize) { | |
| int start = i; | |
| int end = Math.min(i + chunkSize, usuarios.size()); | |
| tareas.add(() -> { | |
| List<String> parcial = new ArrayList<>(); | |
| for (int j = start; j < end; j++) { | |
| Usuario user = usuarios.get(j); | |
| if (user.getEdad() > 18) { | |
| parcial.add(user.getNombre().toUpperCase()); | |
| } | |
| } | |
| return parcial; | |
| }); | |
| } | |
| List<Future<List<String>>> resultados = executor.invokeAll(tareas); | |
| List<String> nombresMayuscula = new ArrayList<>(); | |
| for (Future<List<String>> f : resultados) { | |
| nombresMayuscula.addAll(f.get()); | |
| } | |
| executor.shutdown(); | |
| ### Version2 | |
| class ProcesadorUsuarios extends RecursiveTask<List<String>> { | |
| private static final int UMBRAL = 1000; | |
| private final List<Usuario> usuarios; | |
| ProcesadorUsuarios(List<Usuario> usuarios) { this.usuarios = usuarios; } | |
| @Override | |
| protected List<String> compute() { | |
| if (usuarios.size() <= UMBRAL) { | |
| List<String> res = new ArrayList<>(); | |
| for (Usuario u : usuarios) { | |
| if (u.getEdad() > 18) res.add(u.getNombre().toUpperCase()); | |
| } | |
| return res; | |
| } else { | |
| int mid = usuarios.size() / 2; | |
| ProcesadorUsuarios izquierda = new ProcesadorUsuarios(usuarios.subList(0, mid)); | |
| ProcesadorUsuarios derecha = new ProcesadorUsuarios(usuarios.subList(mid, usuarios.size())); | |
| izquierda.fork(); | |
| List<String> der = derecha.compute(); | |
| List<String> izq = izquierda.join(); | |
| izq.addAll(der); | |
| return izq; | |
| } | |
| } | |
| } | |
| ForkJoinPool pool = new ForkJoinPool(); | |
| List<String> resultado = pool.invoke(new ProcesadorUsuarios(usuarios)); | |
| ### La versión funcional: | |
| List<String> nombresMayuscula = usuarios.parallelStream() | |
| .filter(user -> user.getEdad() > 18) | |
| .map(user -> user.getNombre().toUpperCase()) | |
| .collect(Collectors.toList()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment