Skip to content

Commit

Permalink
feat(lambda): 🎸 built-in interfaces, translated
Browse files Browse the repository at this point in the history
Refers: #6
  • Loading branch information
rcmoutinho committed Sep 12, 2019
1 parent 322d571 commit 8064241
Show file tree
Hide file tree
Showing 19 changed files with 165 additions and 167 deletions.
151 changes: 74 additions & 77 deletions book/04-lambda/sections/03-built-in-interfaces.asc

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ public class BuiltInInterfaces_ConsumerExample {

// tag::code[]
public static void main(String[] args) {
Consumer<Object> impressor = x -> System.out.println(x);
impressor.accept(LocalDate.now()); // imprimirá a data atual
Consumer<Object> printer = x -> System.out.println(x);
printer.accept(LocalDate.now()); // will print the current date

BiConsumer<Object, Object> impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); };
impressor2.accept(LocalDate.now(), LocalTime.now()); // imprimirá a data atual e depois a hora atual
BiConsumer<Object, Object> printer2 = (x, y) -> { System.out.println(x); System.out.println(y); };
printer2.accept(LocalDate.now(), LocalTime.now()); // will print the current date and then the current time
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ public class BuiltInInterfaces_ConsumerPrimitive {

// tag::code[]
public static void main(String[] args) {
IntConsumer impressor = x -> System.out.println(x);
impressor.accept(5); // imprimirá '5'
IntConsumer printer = x -> System.out.println(x);
printer.accept(5); // will print '5'

ObjIntConsumer<Object> impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); };
impressor2.accept(LocalDate.now(), 5); // imprimirá a data atual e depois '5'
ObjIntConsumer<Object> printer2 = (x, y) -> { System.out.println(x); System.out.println(y); };
printer2.accept(LocalDate.now(), 5); // will print the current date and then '5'
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ public class BuiltInInterfaces_FunctionExample {

// tag::code[]
public static void main(String[] args) {
Function<Integer, Double> duplica = x -> x * 2.5;
System.out.println(duplica.apply(3)); // multiplica 3 * 2.5
Function<Integer, Double> duplicate = x -> x * 2.5;
System.out.println(duplicate.apply(3)); // multiply 3 * 2.5

BiFunction<Integer, Integer, Double> multiplicaEDuplica = (x, y) -> x * y * 2.5;
System.out.println(multiplicaEDuplica.apply(3, 4)); // multiplica 3 * 4 * 2.5
BiFunction<Integer, Integer, Double> multiplyAndDuplicate = (x, y) -> x * y * 2.5;
System.out.println(multiplyAndDuplicate.apply(3, 4)); // multiply 3 * 4 * 2.5
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
package org.j6toj8.lambda.builtininterfaces;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntToDoubleFunction;
import java.util.function.ToDoubleBiFunction;

public class BuiltInInterfaces_FunctionPrimitive {

// tag::code[]
public static void main(String[] args) {
IntToDoubleFunction duplica = x -> x * 2.5;
System.out.println(duplica.applyAsDouble(3)); // multiplica 3 * 2.5
IntToDoubleFunction duplicate = x -> x * 2.5;
System.out.println(duplicate.applyAsDouble(3)); // multiply 3 * 2.5

ToDoubleBiFunction<Integer, Integer> multiplicaEDuplica = (x, y) -> x * y * 2.5;
System.out.println(multiplicaEDuplica.applyAsDouble(3, 4)); // multiplica 3 * 4 * 2.5
ToDoubleBiFunction<Integer, Integer> multiplyAndDuplicate = (x, y) -> x * y * 2.5;
System.out.println(multiplyAndDuplicate.applyAsDouble(3, 4)); // multiply 3 * 4 * 2.5
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ public class BuiltInInterfaces_OperatorExample {

// tag::code[]
public static void main(String[] args) {
UnaryOperator<Integer> somaDois = x -> x + 2;
System.out.println(somaDois.apply(7)); // soma 7 + 2
UnaryOperator<Integer> sumTwo = x -> x + 2;
System.out.println(sumTwo.apply(7)); // sum 7 + 2

BinaryOperator<Integer> somaNumeros = (x, y) -> x + y;
System.out.println(somaNumeros.apply(1, 5)); // soma 1 + 5
BinaryOperator<Integer> sumNumbers = (x, y) -> x + y;
System.out.println(sumNumbers.apply(1, 5)); // sum 1 + 5
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ public class BuiltInInterfaces_OperatorPrimitive {

// tag::code[]
public static void main(String[] args) {
IntUnaryOperator somaDois = x -> x + 2;
System.out.println(somaDois.applyAsInt(7)); // soma 7 + 2
IntUnaryOperator sumTwo = x -> x + 2;
System.out.println(sumTwo.applyAsInt(7)); // sum 7 + 2

IntBinaryOperator somaNumeros = (x, y) -> x + y;
System.out.println(somaNumeros.applyAsInt(1, 5)); // soma 1 + 5
IntBinaryOperator sumNumbers = (x, y) -> x + y;
System.out.println(sumNumbers.applyAsInt(1, 5)); // sum 1 + 5
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,33 @@
public class BuiltInInterfaces_OptionalCreation {

// tag::code[]
// Exemplo de método sem Optional
private static String recupereNomeMes(int mes) {
if (mes == 1) {
return "Janeiro";
// method example without Optional
private static String retrieveMonthName(int month) {
if (month == 1) {
return "January";
} else {
return null;
}
}

// Exemplo de método retornando Optional
private static Optional<String> recupereNomeMesOptional(int mes) {
if (mes == 1) {
return Optional.of("Janeiro"); // cria Optional com valor
// method example returning Optional
private static Optional<String> retrieveMonthNameOptional(int month) {
if (month == 1) {
return Optional.of("January"); // create Optional with value
} else {
return Optional.empty(); // cria Optional vazio
return Optional.empty(); // create empty Optional
}
}

public static void main(String[] args) {
String nomeMes1 = recupereNomeMes(1);
if (nomeMes1 != null) { // valida se o valor existe através da tradicional comparação '!= null'
System.out.println(nomeMes1);
String monthName1 = retrieveMonthName(1);
if (monthName1 != null) { // validates if value exists through traditional comparison '! = null'
System.out.println(monthName1);
}

Optional<String> nomeMes2 = recupereNomeMesOptional(1);
if (nomeMes2.isPresent()) { // valida se o Optional possui um valor preenchido
System.out.println(nomeMes2.get()); // recupera o valor dentro do Optional
Optional<String> monthName2 = retrieveMonthNameOptional(1);
if (monthName2.isPresent()) { // validates if Optional has a filled value
System.out.println(monthName2.get()); // retrieve value within Optional
}
}
// end::code[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ public class BuiltInInterfaces_OptionalGetEmpty {

public static void main(String[] args) {
// tag::code[]
Optional<String> optionalComValor = Optional.of("valor");
System.out.println(optionalComValor.get()); // recupera o valor corretamente
Optional<String> optionalWithValue = Optional.of("value");
System.out.println(optionalWithValue.get()); // retrieve value correctly

Optional<String> optionalVazio = Optional.empty();
System.out.println(optionalVazio.get()); // lança exceção
Optional<String> emptyOptional = Optional.empty();
System.out.println(emptyOptional.get()); // throws exception
// end::code[]
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ public class BuiltInInterfaces_OptionalIfPresent {

// tag::code[]
public static void main(String[] args) {
Optional<String> optionalVazio = Optional.empty();
Optional<String> optionalComValor = Optional.of("valor");
Optional<String> emptyOptional = Optional.empty();
Optional<String> optionalWithValue = Optional.of("value");

// A linha abaixo não irá imprimir nada, pois o optional está vazio
optionalVazio.ifPresent(valor -> System.out.println("Vazio: " + valor));
// A linha abaixo irá imprimir, pois o optional possui valor
optionalComValor.ifPresent(valor -> System.out.println("Com Valor: " + valor ));
// The line below will not print anything as optional is empty
emptyOptional.ifPresent(value -> System.out.println("Empty: " + value));
// The line below will print, as optional has value
optionalWithValue.ifPresent(value -> System.out.println("With Value: " + value ));
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ public class BuiltInInterfaces_OptionalNullable {

// tag::code[]
public static void main(String[] args) {
// Exemplo tentando utilizar .of e passando 'null' como argumento
// Example trying to use .of and passing 'null' as argument
try {
Optional.of(null); // Lança NullPointerException nesta linha
Optional.of(null); // Throws NullPointerException on this line
} catch (Exception e) {
e.printStackTrace();
}

// Exemplo utilizando o método correto: .ofNullable
// Example using the correct method: .ofNullable
Optional<String> ofNullable = Optional.ofNullable(null); // Cria um Optional vazio
System.out.println(ofNullable.isPresent()); // Imprime 'false' pois não possui valor
System.out.println(ofNullable.isPresent()); // Print 'false' as it has no value
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ public class BuiltInInterfaces_OptionalOrElse {

// tag::code[]
public static void main(String[] args) {
// Exemplo com Optional vazio
Optional<String> optionalVazio = Optional.empty();
// Example with empty Optional
Optional<String> emptyOptional = Optional.empty();

// as duas variáveis abaixo terão a String "valor padrao", pois o optional está vazio
String orElse = optionalVazio.orElse("valor padrao"); // obtém a String diretamente
String orElseGet = optionalVazio.orElseGet(() -> { return "valor padrao"; }); // obtém a String através da expressão lambda
// the two variables below will have the string "default value" because optional is empty
String orElse = emptyOptional.orElse("default value"); // get the String directly
String orElseGet = emptyOptional.orElseGet(() -> { return "default value"; }); // get String through lambda expression

System.out.println(orElse);
System.out.println(orElseGet);

// Exemplo com Optional com valor
Optional<String> optionalComValor = Optional.of("valor");
// Example with Optional with value
Optional<String> optionalWithValue = Optional.of("value");

// as duas variáveis abaixo irão utilizar o valor presente no optional, pois ele já está preenchido
String orElse2 = optionalComValor.orElse("valor padrao");
String orElseGet2 = optionalComValor.orElseGet(() -> { return "valor padrao"; });
// the two variables below will use the value present in optional as it is already filled
String orElse2 = optionalWithValue.orElse("default value");
String orElseGet2 = optionalWithValue.orElseGet(() -> { return "default value"; });

System.out.println(orElse2);
System.out.println(orElseGet2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ public class BuiltInInterfaces_OptionalOrElseThrow {

// tag::code[]
public static void main(String[] args) {
Optional<String> optionalVazio = Optional.empty();
Optional<String> optionalComValor = Optional.of("valor");
Optional<String> emptyOptional = Optional.empty();
Optional<String> optionalWithValue = Optional.of("value");

// Nesse caso será impresso o valor presente em Optional, pois ele está preenchido
String orElseThrow1 = optionalComValor.orElseThrow(() -> new RuntimeException());
// In this case the value present in Optional will be printed as it is filled
String orElseThrow1 = optionalWithValue.orElseThrow(() -> new RuntimeException());
System.out.println(orElseThrow1);

// Nesse caso será lançada exceção, pois o Optional não está preenchido
String orElseThrow2 = optionalVazio.orElseThrow(() -> new RuntimeException());
// In this case exception will be thrown because Optional is not populated
String orElseThrow2 = emptyOptional.orElseThrow(() -> new RuntimeException());
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ public class BuiltInInterfaces_OptionalPrimitive {

public static void main(String[] args) {
// tag::code[]
OptionalInt optionalComValor = OptionalInt.of(5);
OptionalInt optionalVazio = OptionalInt.empty();
OptionalInt optionalWithValue = OptionalInt.of(5);
OptionalInt emptyOptional = OptionalInt.empty();

if (optionalComValor.isPresent()) {
System.out.println(optionalComValor.getAsInt());
if (optionalWithValue.isPresent()) {
System.out.println(optionalWithValue.getAsInt());
}
if (optionalVazio.isPresent()) {
System.out.println(optionalVazio.getAsInt());
if (emptyOptional.isPresent()) {
System.out.println(emptyOptional.getAsInt());
}
// end::code[]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ public class BuiltInInterfaces_PredicateExample {

// tag::code[]
public static void main(String[] args) {
Predicate<Integer> dado = x -> x.equals(new Random().nextInt(7));
System.out.println(dado.test(1)); // testa se o número gerado é igual a 1
Predicate<Integer> dice = x -> x.equals(new Random().nextInt(7));
System.out.println(dice.test(1)); // tests if the generated number is equal to 1

BiPredicate<Integer, Integer> dadoDuplo = (x, y) -> x.equals(new Random().nextInt(7)) || y.equals(new Random().nextInt(7));
System.out.println(dadoDuplo.test(1, 2)); // testa se o primeiro número gerado é igual a 1
// ou se o segundo número gerado é igual a 2
BiPredicate<Integer, Integer> doubleDice = (x, y) -> x.equals(new Random().nextInt(7)) || y.equals(new Random().nextInt(7));
System.out.println(doubleDice.test(1, 2)); // tests if the first generated number equals 1 or if the second generated number equals 2
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ public class BuiltInInterfaces_PredicatePrimitive {

// tag::code[]
public static void main(String[] args) {
IntPredicate dado = x -> x == new Random().nextInt(7);
System.out.println(dado.test(1)); // testa se o número gerado é igual a 1
IntPredicate dice = x -> x == new Random().nextInt(7);
System.out.println(dice.test(1)); // tests if the generated number is equal to 1
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class BuiltInInterfaces_SupplierExample {
// tag::code[]
public static void main(String[] args) {
Supplier<LocalDate> supplier = () -> LocalDate.now();
System.out.println(supplier.get()); // imprimirá a data atual
System.out.println(supplier.get()); // will print the current date
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class BuiltInInterfaces_SupplierPrimitive {
// tag::code[]
public static void main(String[] args) {
IntSupplier randomIntSupplier = () -> new Random().nextInt();
System.out.println(randomIntSupplier.getAsInt()); // getAsInt retorna um int primitivo
System.out.println(randomIntSupplier.getAsInt()); // getAsInt returns a primitive int
}
// end::code[]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@
public class BuiltInInterfaces_SupplierUseCase {

// tag::code[]
public static String valideIdade(int idade, Supplier<String> supplier) {
if (idade < 18) {
return "Menor de idade!";
public static String validateAge(int age, Supplier<String> supplier) {
if (age < 18) {
return "Under age!";
} else {
return "Maior de idade! Validação realizada às " + supplier.get();
return "Major age! Validation performed at " + supplier.get();
}
}

public static void main(String[] args) {
Supplier<String> supplier = () -> LocalDate.now().atTime(LocalTime.now()).format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(valideIdade(17, supplier));
System.out.println(valideIdade(18, supplier));
System.out.println(validateAge(17, supplier));
System.out.println(validateAge(18, supplier));
}
// end::code[]

Expand Down

0 comments on commit 8064241

Please sign in to comment.