Skip to content

Commit 8a6fe70

Browse files
committed
Composition con ejemplos para compose y andThen
1 parent 8d40e4e commit 8a6fe70

1 file changed

Lines changed: 103 additions & 0 deletions

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
package com.platzi.functional._11_composition;
2+
3+
import java.io.BufferedReader;
4+
import java.io.File;
5+
import java.io.FileReader;
6+
import java.io.IOException;
7+
import java.util.Collections;
8+
import java.util.LinkedList;
9+
import java.util.List;
10+
import java.util.function.Function;
11+
import java.util.stream.Collectors;
12+
13+
public class Composition {
14+
/**
15+
* Dado que las funciones son tipos, podemos almacenarlas como datos en nuestra clase
16+
*/
17+
private static Function<String, File> createFile = path -> new File(path);
18+
19+
/**
20+
* Las funciones pueden ser generadas a partir de una referencia.
21+
*/
22+
private static Function<File, List<String>> linesFromFile = Composition::getLinesFromFile;
23+
24+
private static Function<List<String>, List<String>> filter = list -> {
25+
List<String> resultList = new LinkedList<>();
26+
list.forEach(s -> addIfNotEmpty(resultList, s));
27+
return resultList;
28+
};
29+
30+
/**
31+
* Creamos entonces una funcion simple, que toma un string y nos dara las lineas en ese archivo
32+
* que tengan contenido.
33+
* <p>
34+
* Las lineas sin caracteres no seran consideradas.
35+
*/
36+
static List<String> getLinesWithContentCompose(String pathToFile) {
37+
//Compose toma como parametro una funcion cuyo valor de retorno sea el valor de entrada
38+
//de la funcion desde donde invocamos.
39+
//En este caso:
40+
// 1. `filter` necesita un `List<String>` para poder operar.
41+
// 2. `linesFromFile` genera ese `List` pero necesita un `File` para poder retornar la lista
42+
// 3. `createFile` puede generar un archivo desde un String, que es el parametro de nuestro metodo!
43+
//
44+
// La funcion resultante de invocar a `compose` desde `filter` se ejecuta con el metodo `apply`
45+
return filter
46+
.compose(linesFromFile)
47+
.compose(createFile)
48+
.apply(pathToFile);
49+
}
50+
51+
/**
52+
* Viendo paso a paso cada creacion de funciones que `compose` realiza.
53+
*/
54+
static List<String> stepsGetLinesWithContentCompose(String pathToFile) {
55+
Function<String, List<String>> createFileAndGetLines = linesFromFile.compose(createFile);
56+
57+
Function<String, List<String>> createFileGetLinesFilter = filter.compose(createFileAndGetLines);
58+
59+
return createFileGetLinesFilter.apply(pathToFile);
60+
61+
//Tambien podriamos haber ejecutado la primer funcion y ejecutar filter con el resultado:
62+
63+
// List<String> lines = createFileAndGetLines.apply(pathToFile);
64+
// return filter.apply(lines);
65+
}
66+
67+
static List<String> getLinesWithContent(String pathToFile) {
68+
return createFile
69+
.andThen(linesFromFile)
70+
.andThen(filter)
71+
.apply(pathToFile);
72+
}
73+
74+
static List<String> stepsGetLinesWithContentAndThen(String pathToFile) {
75+
Function<String, List<String>> createFileAndGetLines = createFile.andThen(linesFromFile);
76+
77+
Function<String, List<String>> createFileGetLinesAndFilter = createFileAndGetLines.andThen(filter);
78+
79+
return createFileGetLinesAndFilter.apply(pathToFile);
80+
}
81+
82+
public static void main(String[] args) {
83+
String pathToFile = "/path/to/file.extension";
84+
85+
System.out.println(
86+
getLinesWithContentCompose(pathToFile)
87+
);
88+
}
89+
90+
91+
private static List<String> getLinesFromFile(File file) {
92+
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
93+
return br.lines().collect(Collectors.toList());
94+
} catch (IOException fileNotFoundEx) {
95+
fileNotFoundEx.printStackTrace();
96+
}
97+
return Collections.emptyList();
98+
}
99+
100+
private static void addIfNotEmpty(List<String> list, String s) {
101+
if (s != null && s.length() > 0 && s.trim().length() > 0) list.add(s);
102+
}
103+
}

0 commit comments

Comments
 (0)