Skip to content

mejoras al projecto original #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 115 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
115 commits
Select commit Hold shift + click to select a range
b2b7d8f
Ejemplo de funcion pura agregado
sierisimo Dec 12, 2019
b577b6c
Agregando ejemplo de side effects
sierisimo Dec 12, 2019
6dee3d2
Ejemplos de mutabilidad en java
sierisimo Dec 12, 2019
79f378b
Ejemplo practico de funciones en Java
sierisimo Dec 12, 2019
0ac36f5
Ejemplos de uso de las interfaces en java.util.function
sierisimo Dec 12, 2019
cd03cb8
Tema de SAM agregado
sierisimo Dec 12, 2019
fb6c2e3
Ejemplos del operador ::
sierisimo Dec 13, 2019
61ebd8c
Pequenio ejemplo de inferencia de tipos
sierisimo Dec 13, 2019
793385f
Sintaxis de lambdas con comentarios
sierisimo Dec 13, 2019
10b0f48
Las interfaces con metodos default son algo nuevo en java 8
sierisimo Dec 13, 2019
60f95b1
Metodos default con pequenos ejemplos
sierisimo Dec 13, 2019
8d40e4e
Chaining ejemplos con builders y funciones
sierisimo Dec 13, 2019
8a6fe70
Composition con ejemplos para compose y andThen
sierisimo Dec 13, 2019
5ca101a
Ejemplos iniciales sin comentarios
sierisimo Dec 13, 2019
acfc14e
Agregando ejercicio de composicion
sierisimo Dec 13, 2019
9330302
Merge branch '11-composicion-funcional' into 12-currying
sierisimo Dec 13, 2019
83c955e
Currying con comentarios. Dificil concepto, espero que el ejemplo ayu…
sierisimo Dec 14, 2019
4190575
Partial application example
sierisimo Dec 14, 2019
7d143b7
Explicaciones de optionals
sierisimo Dec 15, 2019
54a22d7
Agregando espacios para legibilidad
sierisimo Dec 15, 2019
d938c94
Ejemplo de throw desde optional
sierisimo Dec 15, 2019
b1b8b43
Arreglado error en ejercicios, actualizando datos de streams
sierisimo Dec 15, 2019
5578aba
Agregados comentarios
sierisimo Dec 15, 2019
2ec4b48
Ejemplos de referencia de metodos
sierisimo Dec 16, 2019
25ee996
Explicacion de operaciones y collectors
sierisimo Dec 16, 2019
27fec99
Definicion de operadores intermedios agregada
sierisimo Dec 16, 2019
bdba81f
Operaciones finales con ejemplos
sierisimo Dec 16, 2019
c534f1c
Archivos base para nuestro proyecto
sierisimo Dec 16, 2019
46853e1
Quitando librerias para el siguiente modulo
sierisimo Dec 16, 2019
3b86127
Agregando librerias
sierisimo Dec 16, 2019
40adc4b
README con opciones y ejemplos
sierisimo Dec 16, 2019
916c1e1
Funciones para crear objetos agregadas
sierisimo Dec 16, 2019
4b88119
Funciones de transformacion y ejecucion final
sierisimo Dec 16, 2019
882e2ca
Ejemplo de Math functions
sierisimo Dec 17, 2019
2a44936
CLIArguments y ejemplo de Consumer / Supplier
sierisimo Dec 17, 2019
96e33d8
BiFunction examples
sierisimo Dec 17, 2019
6116083
Ejemplo de FunctionalInterface
sierisimo Dec 17, 2019
870bf77
Referencias referencias y mas referencias
sierisimo Dec 17, 2019
dd8013b
Ejemplo directo con referencia a metodos
sierisimo Dec 17, 2019
8f50e8e
Merge branch '04-funciones-en-java' into ejemplos-en-clase
sierisimo Dec 17, 2019
028f425
Merge branch '05-Single-Abstract-Method-SAM' into ejemplos-en-clase
sierisimo Dec 17, 2019
8d3ed9a
quitando ejemplos no vistos en clase
sierisimo Dec 17, 2019
1ab2f05
Elminando ejemplos fuera de clase
sierisimo Dec 17, 2019
c4749a5
quitando ejemplos no vistos en clase
sierisimo Dec 17, 2019
7cc5bed
Merge branch '07-inferencia-de-tipos' into ejemplos-en-clase
sierisimo Dec 17, 2019
aa5dcc4
Ejemplo no usado, removido
sierisimo Dec 17, 2019
933732b
Ejemplo de inferencia de tipos
sierisimo Dec 17, 2019
93b5b27
Ejemplo de inferencia de tipos visto en clase
sierisimo Dec 17, 2019
04c030d
usos y sintaxis para lambdas
sierisimo Dec 17, 2019
899bbdb
Merge branch '09-metodos-default' into ejemplos-en-clase
sierisimo Dec 17, 2019
92ed1c8
Borrado de ejemplo no usado
sierisimo Dec 17, 2019
7672660
Ejemplo de metodos default
sierisimo Dec 17, 2019
9592c24
Merge branch '10-chaining' into ejemplos-en-clase
sierisimo Dec 17, 2019
cb94352
Ejemplos no usados en clase, borrados
sierisimo Dec 17, 2019
daa33b3
Chaining y chainer
sierisimo Dec 17, 2019
f392f85
Merge branch '11-composicion-funcional' into ejemplos-en-clase
sierisimo Dec 17, 2019
02682dc
Quitado composicion ejemplificado pero no de clase
sierisimo Dec 17, 2019
57e08a6
Agregando el ejemplo para operaciones
sierisimo Dec 17, 2019
4e152f5
Merge branch '14-optionals' into ejemplos-en-clase
sierisimo Dec 18, 2019
f1a0005
Quitando ejemplos no mostrados en clase
sierisimo Dec 18, 2019
5f0fc47
ejemplos con la clase optional mostrados en clase
sierisimo Dec 18, 2019
68a7939
Ejemplo de IntStream con paralelismo
sierisimo Dec 18, 2019
39c4539
Usando Collectors para convertir Streams
sierisimo Dec 18, 2019
668dbf7
first commit on course platzi java functional programing
MartinFiorde Jun 22, 2024
5411e82
Revert "quitando ejemplos no vistos en clase"
MartinFiorde Jun 22, 2024
6b85fca
Revert "Elminando ejemplos fuera de clase"
MartinFiorde Jun 22, 2024
75183f0
Revert "quitando ejemplos no vistos en clase"
MartinFiorde Jun 22, 2024
8a94f83
Revert "Ejemplo no usado, removido"
MartinFiorde Jun 22, 2024
a174470
Revert "Borrado de ejemplo no usado"
MartinFiorde Jun 22, 2024
3fa3891
rename to avoid conflict on revert
MartinFiorde Jun 22, 2024
8d6af0b
Revert "Ejemplos no usados en clase, borrados"
MartinFiorde Jun 22, 2024
d78b609
Revert "Quitado composicion ejemplificado pero no de clase"
MartinFiorde Jun 22, 2024
8fbad39
Revert "Quitando ejemplos no mostrados en clase"
MartinFiorde Jun 22, 2024
c4a83fd
Merge branch 'job-search' of https://github.com/MartinFiorde/platzi-j…
MartinFiorde Jun 22, 2024
3f8524f
change package "functional" to "functional_teacher_theory"
MartinFiorde Jun 22, 2024
c2674d6
add package "functional_student_practice" to start class 11 practice
MartinFiorde Jun 22, 2024
e0b2606
Merge pull request #1 from MartinFiorde/refactor/starting-point
MartinFiorde Jun 22, 2024
7934f1a
Merge pull request #2 from MartinFiorde/main-fork
MartinFiorde Jun 22, 2024
840235c
class 11
MartinFiorde Jun 22, 2024
3182c62
class 12 lambdas y Predicate
MartinFiorde Jun 22, 2024
2561ef2
class 13 consumers and suppliers
MartinFiorde Jun 22, 2024
d1dba30
implemented supplier and consumer
MartinFiorde Jun 22, 2024
d874c80
class 14 BiFunction and BinaryOperator
MartinFiorde Jun 22, 2024
87ff996
class 15 sam and FunctionalInterface
MartinFiorde Jun 23, 2024
cae537b
class 8 inmutable and update to java17 for tests with List.of()
MartinFiorde Jun 25, 2024
9a5f76d
class 8 improve doc
MartinFiorde Jun 25, 2024
30ab6c8
class 16 reference operator "::"
MartinFiorde Jun 25, 2024
3eb4015
fix linter
MartinFiorde Jun 25, 2024
ef6d8a2
update gradle version
MartinFiorde Jun 28, 2024
b7ea30c
added study docs
MartinFiorde Jun 28, 2024
fdf50b5
class 17 inference
MartinFiorde Jun 28, 2024
d04ad7d
fix
MartinFiorde Jun 28, 2024
442c370
final fix. proyect compatible with java21
MartinFiorde Jun 28, 2024
d774b40
fix linter
MartinFiorde Jun 28, 2024
aec0ecb
fix and unified build.gradle files
MartinFiorde Jun 28, 2024
e3e5b58
fix
MartinFiorde Jun 28, 2024
fa947b2
class 18 lambda syntax
MartinFiorde Jun 29, 2024
dce25e9
fix on examples, updated dependencies versions
MartinFiorde Jun 29, 2024
82a97e1
class 19 default methods in interfaces
MartinFiorde Jun 29, 2024
507a4e4
class 20 chaining
MartinFiorde Jul 2, 2024
bd42aa7
class 21 composition
MartinFiorde Jul 2, 2024
bd25b45
change folder name
MartinFiorde Jul 4, 2024
0ce882c
class 21 theory improved
MartinFiorde Jul 23, 2024
fba7470
refactor file name changes
MartinFiorde Jul 23, 2024
f35f34f
class 22 Optional
MartinFiorde Jul 23, 2024
4e0d379
class 23 24 streams
MartinFiorde Jul 24, 2024
e1fb8d5
class 26 29 Streams advanced methods
MartinFiorde Jul 24, 2024
214c2e3
class 25 27 28 Streams theory
MartinFiorde Jul 24, 2024
5a03ed7
Merge pull request #3 from MartinFiorde/maf-practice
MartinFiorde Jul 24, 2024
b768f15
Merge pull request #4 from MartinFiorde/main-fork
MartinFiorde Jul 24, 2024
5436cee
class 30-40 JobSearchReporter
MartinFiorde Jul 24, 2024
ea5855a
mejoras varias
MartinFiorde Jul 24, 2024
d5e952c
Merge pull request #5 from MartinFiorde/maf-practice
MartinFiorde Jul 24, 2024
e7b21a3
Clear of personal practice. Keep global config for java 21 and better…
MartinFiorde Jul 24, 2024
2430990
Merge pull request #6 from MartinFiorde/refactor/clean-personal-practice
MartinFiorde Jul 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed docs/Apuntes java functional.docx
Binary file not shown.
Binary file removed docs/Functional SE.pdf
Binary file not shown.
Binary file removed docs/java 8 streams cheatsheet.webp
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,6 @@
import java.util.function.Supplier;

public interface CommanderFunctions {
/**
* JCommander permite generar opciones de terminal de cualquier clase, por eso el primer parametro es
* de tipo Object.
*
* @param object Clase de la cual se generaran los argumentos de JCommander
* @return una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
*/
static JCommander buildCommander(Object object) {
return JCommander
.newBuilder()
.addObject(object)
.build();
}

/**
* Con esta funcion, facilitamos crear una configuracion inicial de JCommander, pidiendo el nombre del
* programa y un Supplier de tipo T para los argumentos. Asi podemos usar alguna funcion que nos devuelva
Expand All @@ -33,7 +19,11 @@ static JCommander buildCommander(Object object) {
* @return una instancia de {@link JCommander} ya configurada con el nombre y los argumentos.
*/
static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsSupplier) {
JCommander jCommander = buildCommander(argumentsSupplier.get());
// JCommander permite generar opciones de terminal de cualquier clase, por eso se le agrega un object con el metodo addObject(...)
// argumentsSupplier.get() es la clase de la cual se generaran los argumentos de JCommander
// Queda definida una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
JCommander jCommander = JCommander.newBuilder().addObject(argumentsSupplier.get()).build();

jCommander.setProgramName(name);
return jCommander;
}
Expand All @@ -45,18 +35,14 @@ static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsS
static Optional<List<Object>> parseArguments(
JCommander jCommander,
String[] arguments,
OnCommandError onCommandError
) {
List<Object> result;
OnCommandError onCommandError) { // en caso que las validaciones de CLIKeywordValidaror o CLIHelpValidator fallen, se generará un ParameterException
try {
jCommander.parse(arguments);

return Optional.of(jCommander.getObjects());
} catch (ParameterException exception) {
} catch (ParameterException exception) { // atrapará el parameter exception y devuelve un optional vacio
onCommandError.onError(jCommander);
return Optional.empty();
}

return Optional.empty();
}

@FunctionalInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,22 @@ public static void main(String[] args) {
JCommander jCommander = buildCommanderWithName("job-search", CLIArguments::newInstance);

//Obtenemos las opciones que se le dieron a JCommander
Stream<CLIArguments> streamOfCLI =
//Nos retorna un Optional<List<Object>>
parseArguments(jCommander, args, JCommander::usage)
//En caso de un Optional.empty()
.orElse(Collections.emptyList())
Stream<CLIArguments> streamOfCLI = parseArguments(jCommander, args, JCommander::usage) //Nos retorna un Optional<List<Object>>
.orElse(Collections.emptyList()) //En caso de un Optional.empty()
.stream()
.map(CLIArguments.class::cast); // map(obj -> (CLIArguments) obj) give same result

//Tomamos nuestro Stream y obtenemos las opciones que se dieron en el CLI
Optional<CLIArguments> cliOptional = streamOfCLI
//Solo nos interesan los casos donde no sea la solicitud de ayuda
.filter(cli -> !cli.isHelp())
//Y que contengan un keyword, en otros caso no tenemos que buscar
.filter(cli -> cli.getKeyword() != null)
.filter(cli -> !cli.isHelp()) //Solo nos interesan los casos donde no sea la solicitud de ayuda
.filter(cli -> cli.getKeyword() != null) //Y que contengan un keyword, en otros caso no tenemos que buscar
.findFirst();

//Si el Optional tiene un dato, lo convertimos a Map<String,Object>
cliOptional.map(CLIFunctions::toMap)
//Convertimos el Map en un request
.map(JobSearch::executeRequest)
//Aun seguimos operando sobre un Optional… en caso de que no hubiera datos
//Generamos un stream vacio
.orElse(Stream.empty())
//Imprimos los datos por pantalla.
.forEach(System.out::println);
.map(JobSearch::executeRequest) //Convertimos el Map en un request
.orElse(Stream.empty()) //Aun seguimos operando sobre un Optional… en caso de que no hubiera datos generamos un stream vacio
.forEach(System.out::println); //Imprimos los datos por pantalla.
}

private static Stream<JobPosition> executeRequest(Map<String, Object> options) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public final class CLIArguments {
private boolean isMarkdown = false;

@Parameter(
names = "--help",
names = {"--help", "-h"},
help = true,
validateWith = CLIHelpValidator.class,
description = "Muestra esta ayuda")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public class CLIKeywordValidator implements IParameterValidator {
@Override
public void validate(String name, String value) throws ParameterException {
if (!value.matches("^[a-zA-Z]+[0-9]*$")) {
if (!value.matches("^[a-zA-Z]+\\d*$")) {
System.err.println("Keyword: " + value + " no es un Keyword valido, keywords deben ser alfanumericas.\n");
throw new ParameterException("Only alphanumerics are supported");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,66 +1,4 @@
package com.platzi.functional_student_practice._03_inmutable;

import java.util.List;

public class C8InmutObjWithMutAttributes {

public static void main(String[] args) {

System.out.println("////////////////////////////////////////////////////////////////////////////////////");
System.out.println("\nCLASS 8\n");

// 1. We make an inmutable object (without setters)
Direccion dir = new Direccion("New York");

// 2. We make a mutable object (with setters)
Persona p1 = new Persona(dir);

// 3. We make an inmutable list
List<Persona> lista1 = List.of(p1);

// 4. Try to change mutable element from inmutable list is allowed
System.out.println("Antes de modificar: " + lista1);
p1.getDireccion().setCiudad("Los Angeles");
System.out.println("Después de modificar: " + lista1);

}

private static class Direccion {
String ciudad;

Direccion(String ciudad) {
this.ciudad = ciudad;
}

String getCiudad() {
return ciudad;
}

void setCiudad(String ciudad) {
this.ciudad = ciudad;
}

@Override
public String toString() {
return ciudad;
}
}

private static class Persona {
private final Direccion direccion;

Persona(Direccion direccion) {
this.direccion = direccion;
}

public Direccion getDireccion() {
return direccion;
}

@Override
public String toString() {
return "Persona{direccion=" + direccion + "}";
}
}

}
Original file line number Diff line number Diff line change
@@ -1,74 +1,4 @@
package com.platzi.functional_student_practice._04_functional;

import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.Predicate;

public class C11y12MathFunctions {
public static void main(String[] args) {

System.out.println("////////////////////////////////////////////////////////////////////////////////////");
System.out.println("\nCLASS 11\n");

// 1. function as type
// Function<Integer, Integer> square1 = new Function<Integer, Integer>() {
// @Override
// public Integer apply(Integer x) {
// return x * x;
// }
// };
// System.out.println(square1.apply(5)+"\n");

// 2. function 1 writen in a more performant way
IntUnaryOperator square2 = x -> x * x;
System.out.println(square2.applyAsInt(6)+"\n");

// 3. function 3 declared in the class, outside the main method
System.out.println(square3(7));
System.out.println(square3(8)+"\n");


System.out.println("////////////////////////////////////////////////////////////////////////////////////");
System.out.println("\nCLASS 12\n");

// 1. Function as type using lambda to declare operation in one line
// Function<Integer, Boolean> isOdd1 = x -> x % 2 == 1;
// System.out.println(isOdd1.apply(7));
// System.out.println(isOdd1.apply(8)+"\n");

// 2. function 1 writen in a more performant way
IntPredicate isOdd2 = x -> x % 2 == 1;
System.out.println(isOdd2.test(7));
System.out.println(isOdd2.test(8)+"\n");

// 3. function Predicate by teacher
// Predicate<Integer> isEven1 = x -> x % 2 == 0;
// System.out.println(isEven1.test(7));
// System.out.println(isEven1.test(8)+"\n");

// 4. function 3 performant
IntPredicate isEven2 = x -> x % 2 == 0;
System.out.println(isEven2.test(7));
System.out.println(isEven2.test(8)+"\n");

// 5. Student example
Predicate<Student> isApproved = student -> student.getQualification()>= 7;
System.out.println(isApproved.test(new Student(6)));
System.out.println(isApproved.test(new Student(7)));
}

private static int square3(int x) {
return x * x;
}

private static class Student {
private final double qualification;
public Student(double qualification) {
this.qualification = qualification;
}
public double getQualification() {
return qualification;
}
}

}
Original file line number Diff line number Diff line change
@@ -1,57 +1,4 @@
package com.platzi.functional_student_practice._04_functional;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class C13CLIUtils {

public static void main(String[] args) {

System.out.println("////////////////////////////////////////////////////////////////////////////////////\n");
System.out.println("CLASS 13\n");

// 1. Created CLI class, consumer and supplier
List<CLIArguments> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(generateCLI());
list.get(i).setHelp(i % 2 == 0);
}

for (int i = 0; i < list.size(); i++) {
showHelp(list.get(i), i);
}

}


private static void showHelp(CLIArguments cliArguments, int i) {
Consumer<CLIArguments> consumerHelper = cliArguments1 -> {
if (cliArguments1.isHelp()) {
System.out.println(i +": Manual required");
}
};
consumerHelper.accept(cliArguments);
}


private static CLIArguments generateCLI() {
Supplier<CLIArguments> generator = CLIArguments::new; //same as () -> new CLIArguments()
return generator.get();
}


private static class CLIArguments {
private boolean isHelp;

public boolean isHelp() {
return isHelp;
}

public void setHelp(boolean help) {
isHelp = help;
}
}

}
Original file line number Diff line number Diff line change
@@ -1,46 +1,4 @@
package com.platzi.functional_student_practice._04_functional;

import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.IntBinaryOperator;
import java.util.function.UnaryOperator;

public class C14StringFunctions {

public static void main(String[] args) {

System.out.println("////////////////////////////////////////////////////////////////////////////////////\n");
System.out.println("CLASS 14\n");

// 1. Unary operators are a Function class where input and return types match
final String SALUTE = "Hi programing student";
UnaryOperator<String> quote = text -> "\"" + text + "\"";
System.out.println(quote.apply(SALUTE));

UnaryOperator<String> addMark = text -> text + "!";
System.out.println(quote.apply(addMark.apply(SALUTE)) + "\n");

// 2. BiFunction class is a Function class that accept 2 parameters and return another
BiFunction<Integer, Integer, Integer> multiply1 = (x, y) -> x * y;
System.out.println(multiply1.apply(5, 4));

// 3. function 2 improved
BinaryOperator<Integer> multiply2 = (x, y) -> x * y;
System.out.println(multiply2.apply(5, 4));

// 4. function 3 improved
IntBinaryOperator multiply3 = (x, y) -> x * y;
System.out.println(multiply3.applyAsInt(5, 4) + "\n");

// 5. BiFunction with mixed types
BiFunction<String, Integer, String> leftPad = (text, number) -> {
String formatSpecifier = "%" + number + "s"; //add spaces up to making a string of n characters
return String.format(formatSpecifier, text);
};
System.out.println(leftPad.apply("Java", 10) + "\n");


}


}
Original file line number Diff line number Diff line change
@@ -1,35 +1,4 @@
package com.platzi.functional_student_practice._05_sam;

import java.time.LocalDate;
import java.time.Period;
import java.util.function.IntFunction;

public class C15AgeUtils {

public static void main(String[] args) {

System.out.println("////////////////////////////////////////////////////////////////////////////////////");
System.out.println("\nCLASS 15\n");

// 1. We declare a function to format integers for parser
IntFunction<String> addCero = num -> num < 10 ? "0" + num : "" + num;

// 2. We parse integers into a LocalDate object
TriFunction<Integer, Integer, Integer, LocalDate> formatDate =
(dd, mm, yyyy) -> LocalDate.parse(yyyy + "-" + addCero.apply(mm) + "-" + addCero.apply(dd));

// 3. we calculate
TriFunction<Integer, Integer, Integer, Integer> calculateAge =
(d, m, y) -> Period.between(formatDate.apply(d, m, y), LocalDate.now()).getYears();

System.out.println(calculateAge.apply(24,6,2014));

}

// 0. We declare a FunctionalInterface to implement in our cude
@FunctionalInterface
interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}

}
Loading