Created
October 27, 2023 12:42
-
-
Save Awes0meM4n/422064d3ed762b85100b192edf9a7b24 to your computer and use it in GitHub Desktop.
Emparejar elementos de una lista
This file contains 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
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collection; | |
import java.util.List; | |
import java.util.UUID; | |
import java.util.function.BiFunction; | |
import java.util.function.BinaryOperator; | |
public class AgruparPorPares { | |
public static void main(String[] args) { | |
Collection<Cuenta> cuentas = new ArrayList<>(); | |
for (String nombre : Arrays.asList("Jose", "Maria", "Antonio", "Luisa", "Juan", "Norma", "Pedro")) { | |
cuentas.add(new Cuenta(nombre)); | |
} | |
// Es menos complicado hacer un bucle y mas facil de leer | |
// List<Cuenta[]> pares = new ArrayList<>(); | |
// Cuenta[] par = null; | |
// for (Cuenta element : cuentas) { | |
// if (par == null) { | |
// par = new Cuenta[] { element, null }; | |
// pares.add(par); | |
// } else { | |
// par[1] = element; | |
// par = null; | |
// } | |
// } | |
// Asi se pueden apreciar bien los tipos que he usado en reduce | |
BinaryOperator<List<Cuenta[]>> combiner = (rp, rc) -> rc; | |
BiFunction<List<Cuenta[]>,? super Cuenta, List<Cuenta[]>> accumulator; | |
accumulator = (List<Cuenta[]> r, Cuenta c) -> { | |
if (r.size() == 0) { | |
r.add(new Cuenta[] { c, null }); | |
} else { | |
Cuenta[] p = r.get(r.size() - 1); | |
if (p[1] != null) { | |
r.add(new Cuenta[] { c, null }); | |
} else { | |
p[1] = c; | |
} | |
} | |
return r; | |
}; | |
List<Cuenta[]> pares = cuentas.stream().reduce(new ArrayList<>(), accumulator, combiner); | |
// Esto seria todo en una sola linea | |
// List<Cuenta[]> pares = cuentas.stream().reduce(new ArrayList<>(), | |
// (List<Cuenta[]> r, Cuenta c) -> { | |
// if (r.size() == 0) { | |
// r.add(new Cuenta[] { c, null }); | |
// } else { | |
// Cuenta[] p = r.get(r.size() - 1); | |
// if (p[1] != null) { | |
// r.add(new Cuenta[] { c, null }); | |
// } else { | |
// p[1] = c; | |
// } | |
// } | |
// | |
// return r; | |
// }, | |
// (rp, rc) -> rc); | |
pares.forEach(p -> System.out.println(p[0].getNumeroCuenta() + " | " + (p[1] != null ? p[1].getNumeroCuenta() : "Desparejado"))); | |
} | |
static class Cuenta { | |
private String nombre, numeroCuenta; | |
public String getNombre() { | |
return nombre; | |
} | |
public String getNumeroCuenta() { | |
return numeroCuenta; | |
} | |
public Cuenta(String nombre) { | |
this.nombre = nombre; | |
numeroCuenta = UUID.randomUUID().toString(); | |
} | |
@Override | |
public String toString() { | |
return getNumeroCuenta(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment