par , 12/07/2015 à 14h01 (1305 Affichages)
En me documentant sur les stream de Java 8, je suis tombé sur le dépôt GitHub du livre Java 8 In Action.
Note : Je n'ai pas lu le livre.
Même sans lire le livre, les exemples données sont assez intéressant. Cela permet de se familiariser avec les nouveautés Java 8, avec des exemples relativement simple (qui compile) et surtout qui sont centré sur un seulement élément à la fois !
Le code en lui-même à tendance à manquer de commentaire. Du coup, j'ai ma propre version avec un peu plus de commentaire ici (Enfin pas beaucoup plus)
Voici un aperçu :
1 2 3 4 5
| System.out.println("Demonstration of Stream.iterate with fibonnaci implemantation (Only the n value)");
Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1],t[0] + t[1]})
.limit(10)
. map(t -> t[0])
.forEach(System.out::println); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package lambdasinaction.chap3;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ExecuteAround {
public static void main(String ...args) throws IOException{
// method we want to refactor to make more flexible
System.out.println("Processing a file with a static method");
String result = processFileLimited();
System.out.println(result);
System.out.println("---");
System.out.println("Processing a file with lamdba implementation of an interface");
String oneLine = processFile((BufferedReader b) -> b.readLine());
System.out.println(oneLine);
System.out.println("Processing a file with an other lamdba implementation");
String twoLines = processFile((BufferedReader b) -> b.readLine() + b.readLine());
System.out.println(twoLines);
}
public static String processFileLimited() throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))) {
return br.readLine();
}
}
public static String processFile(BufferedReaderProcessor p) throws IOException {
try(BufferedReader br = new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))){
return p.process(br);
}
}
public interface BufferedReaderProcessor{
public String process(BufferedReader b) throws IOException;
}
} |
Cordialement,
Patrick Kolodziejczyk.
source :
https://github.com/java8/Java8InAction/
https://github.com/pkolodziejczyk/Java8InAction
Mis à jour 15/07/2015 à 01h33 par kolodz
- Catégories
-
Java