miércoles, 9 de diciembre de 2015

10 ejemplos de uso de Lambda en Java 8

Estos post son buenos, lo que quiere ver un programador es código y encontré una pagina que da ejemplos de uso de Lambda en Java 8 y quiero transcribirlos:

Ejemplo 1 - Implementar Runnable usando Lambda:

Antes:

new Thread(new Runnable() { @Override public void run() { System.out.println("Before Java8, too much code for too little to do"); } }).start();

Ahora:

new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();

Ejemplo 2 - Manejo de eventos:

Antes:

Button show = new JButton("Show"); show.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Event handling without lambda expression is boring"); } });

Ahora:

show.addActionListener((e) -> { System.out.println("Light, Camera, Action !! Lambda expressions Rocks"); });

Ejemplo 3 - Iterar una lista:

Antes:

List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); for (String feature : features) { System.out.println(feature); }

Ahora:

List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));

Ejemplo 4 - Usar Labda para filtrar (como predicado)

public static void main(args[]){ List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
System.out.println("Languages which starts with J :");
filter(languages, (str)->str.startsWith("J"));
System.out.println("Languages which ends with a ");
filter(languages, (str)->str.endsWith("a"));
System.out.println("Print all languages :");
filter(languages, (str)->true);
System.out.println("Print no language : ");
filter(languages, (str)->false);
System.out.println("Print language whose length greater than 4:");
filter(languages, (str)->str.length() > 4); }

public static void filter(List names, Predicate condition) {
for(String name: names) { if(condition.test(name)) { System.out.println(name + " "); } } }
}

Ejemplo 5 - Combinando Predicado y Lambda:

Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
names.stream() .filter(startsWithJ.and(fourLetterLong)) .forEach((n) -> System.out.print("\nName, which starts with 'J' and four letter long is : " + n));


Ejemplo 6 - Map and reduce:

Antes:

List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    System.out.println(price);
}

Ahora:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(System.out::println);

Ejemplo 7 - Creando listas y filtrando:

List<String> filtered = strList.stream().filter(x -> x.length()> 2).collect(Collectors.toList()); System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);

Ejemplo 8 - aplicando una función a cada elemento:

List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada"); String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", ")); System.out.println(G7Countries);

Ejemplo 9 - creando sublistas y filtrando:

List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
System.out.printf("Original List : %s, Square Without duplicates : %s %n", numbers, distinct);

Ejemplo 10 - calculando máximo, mínimo, etc:

List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("Highest prime number in List : " + stats.getMax()); S
ystem.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());

A simple vista se ve muy bueno!

Dejo link:
http://javarevisited.blogspot.com.ar/2014/02/10-example-of-lambda-expressions-in-java8.html