Skip to content

Instantly share code, notes, and snippets.

@Awes0meM4n
Last active January 10, 2021 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Awes0meM4n/ad3894676708a794ebcef9dacf902d85 to your computer and use it in GitHub Desktop.
Save Awes0meM4n/ad3894676708a794ebcef9dacf902d85 to your computer and use it in GitHub Desktop.
Ejemplo de suma de un atributo usando un lambda
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collection;
public class EjemploAcumulador {
public static void main(String[] args) {
// Me creo un Reparable, esto se haria con los tipos del negocio (como Coche)
Reparable reparable = new Reparable() {
@Override
public Collection<EjemploAcumulador.Reparacion> getReparacionesPendientes() {
// Simplemente devuelvo una lista con una reparacion de 1 hora y otra de 2.345
return Arrays.asList(() -> 1, () -> 2.345f);
}
// Este metodo no afecta
@Override
public LocalDate getFechaEntrada() { return null; }
};
System.out.println("Tiempo total: " + calcularTiempoReparacion(reparable) + "h");
// El resultado por consola es: "Tiempo total: 3.345h"
}
public static float calcularTiempoReparacion(Reparable reparable) {
// Este es tu codigo sin lambdas
// float tiempo = 0.0f;
// for (Reparacion reparacion : reparable.getReparacionesPendientes()) {
// tiempo += reparacion.getHorasManoObra();
// }
// return tiempo;
// Este usando lambdas
return (float) reparable.getReparacionesPendientes().stream() // Creo el stream
.mapToDouble(Reparacion::getHorasManoObra) // lo convierto en un DoubleStream
.sum(); // el tipo DoubleStream tiene el metodo sum()
}
// Estos dos tipos de abajo no te hacen falta si ya tienes tu codigo
// En ese caso borralo para que no tengas conflicto
private static interface Reparable {
LocalDate getFechaEntrada();
Collection<Reparacion> getReparacionesPendientes();
}
private static interface Reparacion {
public float getHorasManoObra();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment