diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 1bbb9a3..24cad26 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -39,6 +39,7 @@
+
\ No newline at end of file
diff --git a/A-tricks-to-succeed.asc b/A-tricks-to-succeed.asc
index 0b08e6a..7594056 100644
--- a/A-tricks-to-succeed.asc
+++ b/A-tricks-to-succeed.asc
@@ -1,12 +1,12 @@
[[A-tricks-to-succeed]]
[appendix]
-== Dicas para ter sucesso na prova!
+== Tips to succeed in the test!
-Além de validar conceitos importantes da linguagem Java a prova de certificação também exigirá que você esteja atento a detalhes específicos nos códigos de cada questão. Sem o auxílio da IDE, você será o compilador.
+In addition to validating important Java language concepts, the certification exam will also require you to be aware of specific details in the codes of each question. Without the help of the IDE, you will be the compiler.
-Veja alguns exemplos simples que se mostram óbvios mas podem te enganar na hora de marcar a resposta certa.
+Here are some simple examples that are obvious but can trick you into marking the right answer.
-=== Cenário 1
+=== Scenario 1
[source,java]
----
@@ -19,29 +19,29 @@ class Duke {
}
}
----
-. Compila e imprime "Java6"
-. Compila e imprime "Java8"
-. Não compila
-. Compila, mas ocorre um erro durante a execução
+. Compile and print "Java6"
+. Compile and print "Java8"
+. Not compile
+. Compiles, but an error occurs while running
-Sem pensar muito a reposta seria a _opção 1_, certo? Errado. Olhando mais atentamente ao código é possível notar que na primeira linha do método `main` está faltando um `;` (ponto-e-vírgula). Esse pequeno detalhe mostra que a opção certa é a 3.
+Without thinking too much the answer would be _option 1_, right? Wrong. Looking more closely at the code, you can see that the first line of the `main` method is missing a `;` (semicolon). This little detail shows that the right option is 3.
[TIP]
--
-Sempre que existir uma resposta falando _código não compila_, verifique duas vezes as regras de compilação antes de testar o comportamento do código e sua possível resposta.
+Whenever there is a response saying _code does not compile_, double-check the compilation rules before testing the code's behavior and its possible answer.
-.Checklist mental para validar uma compilação
-* Ponto-e-vírgula
-* Visibilidade
-* Escopo de variáveis
-* Nomes e parâmetros de métodos
+.Mental checklist to validate a build
+* Semicolon
+* Visibility
+* Scope of variables
+* Method names and parameters
* ...
--
- - -
-_Resposta: 3_
+_Answer: 3_
-=== Cenário 2
+=== Scenario 2
[source,java]
----
@@ -54,17 +54,17 @@ class Duke {
}
}
----
-. O código compila e roda, imprimindo "Java8".
-. O código não compila.
-. O código compila e roda, imprimindo "Java6".
-. O código compila mas dá erro em execução.
+. The code compiles and runs, printing "Java8".
+. The code does not compile.
+. The code compiles and runs, printing "Java6".
+. The code compiles but gives error in execution.
-Se você escolheu a opção 1, você errou... Esse exemplo tem outra pegadinha com o conceito de _shadowing_. Usa-se o mesmo nome de váriável mas com um escopo diferente. Inicialmente o tipo `int` engana sua reposta mas esse código não compila ao tentar atribuir um valor `int` à uma variável do tipo `String[]`.
+If you chose option 1, you got it wrong... This example has another catch with the concept of _shadowing_. The same variable name is used but with a different scope. Initially the `int` type misleads its response but this code does not compile when trying to assign an `int` value to a `String[]` variable.
- - -
-_Resposta: 2_
+_Answer: 2_
-=== Cenário 3
+=== Scenario 3
[source,java]
----
@@ -76,26 +76,26 @@ class Duke {
}
}
----
-. Imprime `1`
-. Imprime `0`
-. Imprime `false`
-. Imprime `true`
-. Imprime `null`
-. Erro de execução
-. Não compila
+. Print `1`
+. Print `0`
+. Print false
+. Print `true`
+. Print `null`
+. Execution Error
+. Not compile
-A escolha mais comum seria a opção 3, onde confirma que o valor padrão de cada posição de um array do tipo _boolean_ é _false_. Esta opção estaria certa, se não fosse uma pegadinha. Este código na verdade *não compila*. A opção certa seria a número 7. Isso porque a variável _dukeClones_ é um _boolean_ simples tentando receber um array do tipo _boolean_.
+The most common choice would be option 3, where it confirms that the default value of each position of an array of type _boolean_ is _false_. This option would be right if it wasn't a catch. This code actually *does not compile*. The right option would be number 7. That's because the _dukeClones_ variable is a simple _boolean_ trying to get an array of type _boolean_.
[TIP]
--
-Em uma inicialização implícita como membro de uma classe, ou cada posição de um array, etc, a variável recebe o valor padrão respeitando a seguinte regra:
+In an implicit initialization as a member of a class, or each position of an array, etc., the variable gets the default value respecting the following rule:
* _boolean_ -> *_false_*
-* _char_ -> *vazio*, equivalente a 0
-* Primitivos numéricos inteiros -> *0*
-* Primitivos numéricos com ponto flutuante -> *0.0*
-* Referências (Objetos) -> *_null_*
+* _char_ -> *empty*, equivalent to 0
+* Integer Numeric Primitives -> *0*
+* Floating-point numeric primitives -> *0.0*
+* References (Objects) -> *_null_*
--
- - -
-_Resposta: 7_
+_Answer: 7_
diff --git a/B-test-yourself.asc b/B-test-yourself.asc
index 78d3a23..d5ee471 100644
--- a/B-test-yourself.asc
+++ b/B-test-yourself.asc
@@ -1,18 +1,18 @@
[[B-test-yourself]]
[appendix]
-== Teste seu conhecimento!
+== Test your knowledge!
-Hora de colocar em prática tudo que foi visto neste livro. Existem algumas opções gratuitas e várias opções pagas. A opção mais interessante para ambos os casos é a *Whizlabs*.
+Time to put into practice everything that has been seen in this book. There are some free options and several paid options. The most interesting option for both cases is *Whizlabs*.
-Todos os testes listados abaixo são em inglês, provavelmente o mesmo idioma que você fará seu teste.
+All tests listed below are in English, probably the same language as you will be taking your test.
-IMPORTANT: Todas as opções são referentes à prova _1Z0-813_ (atualização do Java 6 ou inferior para o Java 8).
+IMPORTANT: All options are for test _1Z0-813_ (Java 6 or lower upgrade to Java 8).
-=== Gratuito
+=== Free
[cols="2*^.^"]
|===
-| Link | Qtd. Questões
+| Link | Qty. Questions
| https://www.whizlabs.com/ocpjp-8-upgrade-1z0-813/free-test/[Whizlabs]
| 25
@@ -22,13 +22,13 @@ IMPORTANT: Todas as opções são referentes à prova _1Z0-813_ (atualização d
|===
-=== Pagos
+=== Paid
[cols="3*^.^"]
|===
-| Link | Qtd. Questões | Preço
+| Link | Qty. Questions | Price
-| https://www.whizlabs.com/ocpjp-8-upgrade-1z0-813/practice-tests/[Whizlabs] *(Recomendado)*
+| https://www.whizlabs.com/ocpjp-8-upgrade-1z0-813/practice-tests/[Whizlabs] *(Recommended)*
| 360
| $9.95
@@ -36,13 +36,13 @@ IMPORTANT: Todas as opções são referentes à prova _1Z0-813_ (atualização d
| ?
| $89
-| https://education.oracle.com/certification-epractice-exam-30-day-online-access/courP_2364[Oracle] (30 dias)
+| https://education.oracle.com/certification-epractice-exam-30-day-online-access/courP_2364[Oracle] (30 days)
| ?
-| R$ 169,00
+| $88
-| https://education.oracle.com/certification-epractice-exam-180-day-online-access/courP_8737[Oracle] (180 dias)
+| https://education.oracle.com/certification-epractice-exam-180-day-online-access/courP_8737[Oracle] (180 days)
| ?
-| R$ 290,00
+| $129
| https://www.examcollection.com/1z0-813.html[Exam Collection]
| 61
diff --git a/book/03-localization/sections/01-locale.asc b/book/03-localization/sections/01-locale.asc
index 48ab0e7..8adad51 100644
--- a/book/03-localization/sections/01-locale.asc
+++ b/book/03-localization/sections/01-locale.asc
@@ -1,33 +1,31 @@
:java-package: src/org/j6toj8/localization
:section-java-package: ../../../{java-package}
-=== Localização (Locale)
+=== Locale
-.Objetivo
+.Objective
--------------------------------------------------
Describe the advantages of localizing an application and developing code that defines, reads, and sets the locale with a Locale object.
--
-Descrever as vantagens de localizar uma aplicação e desenvolver código que defina, leia e aplique a localidade em um objeto Locale.
--------------------------------------------------
-É esperado que o candidato saiba compreender e analisar aspectos de Internacionalização e Localização, incluindo o uso da da classe `Locale`.
+The candidate is expected to be able to understand and analyze aspects of Internationalization and Localization, including the use of the `Locale` class.
-Alguns aspectos de uma aplicação podem depender do país e da linguagem. Por exemplo:
+Some aspects of an application may depend on country and language. For example:
-* Formatos de escrita de data
-** O dia 6 de Agosto de 2019 seria representado no Brasil por `06/08/2019`, porém nos EUA seria `08/06/2019`.
-* Formatos de escrita de valores monetários
-** Dez Reais no Brasil seriam representados por `R$ 10`, enquanto na França Dez Euros seriam `10 €`.
-* Formatos de separação de casas decimais ou milhares
-** No Brasil utiliza-se vírgula para separar decimais e pontos para milhares: `100.245,03`. Nos EUA, utiliza-se o inverso: `100,245.03`.
+* Date writing formats
+** August 6, 2019, would be represented in Brazil by `06/08/2019`, but in the USA would be `08/06/2019`.
+* Currency value writing formats
+** Ten Reais in Brazil would be represented by `R$ 10`, while in France Ten Euros would be `10 €`.
+* Decimal or Thousand Separation Formats
+** In Brazil comma is used to separate decimals and points to thousands: `100.245,03`. In the USA, it is the opposite: `100,245.03`.
-Por isso, para que sua aplicação lide corretamente com esses cenários, é necessário compreender dois aspectos: *Internacionalização* (_Internationalization_) e *Localização* (_Localization_).
+Therefore, in order for your application to handle these scenarios correctly, you need to understand two aspects: *Internationalization* and *Localization*.
-A *Internacionalização*, também chamada de *_i18n_*, é o ato de projetar sua aplicação para que seja possível facilmente adaptá-la para utilizar novos formatos e idiomas.
+*Internationalization*, also called *_i18n_*, is the act of designing your application so that you can easily adapt it to use new formats and languages.
-A *Localização*, também chamada de *_l10n_*, é o ato de adaptar sua aplicação para de fato utilizar um novo formato específico.
+*Localization*, also called *_l10n_*, is the act of tailoring your application to actually use a new specific format.
-Antes de continuar, entenda a execução do método `main` no exemplo a seguir e o que é apresentado no console após sua execução.
+Before proceeding, understand the execution of the `main` method in the following example and what is presented on the console after its execution.
[source,java,indent=0]
.{java-package}/locale/Locale_Complete.java
@@ -35,13 +33,13 @@ Antes de continuar, entenda a execução do método `main` no exemplo a seguir e
include::{section-java-package}/locale/Locale_Complete.java[tag=code]
----
-.Saída no console
+.console output
[source,console]
----
- - Constantes -
+ - Constants -
en_CA
en_GB
- - Construtor -
+ - Constructor -
pt_BR
pt_PT
ca_ES_VALENCIA
@@ -57,13 +55,13 @@ az_AZ_#Latn
bs_BA_POSIX_#Latn_c-cc
----
-No Java, a classe `Locale` no pacote `java.util` nos ajuda a lidar com esses aspectos.
+In Java, the `Locale` class in the `java.util` package helps us deal with these aspects.
-. Geralmente, um `Locale` é representado por um idioma e um país.
-* `pt_BR` - Português do Brasil
-* `en_US` - Inglês dos EUA
-* `it_CH` - Italiano da Suíça
-* `fr_BE` - Francês da Bélgica
+. Generally, a `Locale` is represented by a language and a country.
+* `pt_BR` - Brazilian Portuguese
+* `en_US` - US English
+* `it_CH` - Italian from Switzerland
+* `fr_BE` - French from Belgium
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleLanguageCountry.java
@@ -71,7 +69,7 @@ No Java, a classe `Locale` no pacote `java.util` nos ajuda a lidar com esses asp
include::{section-java-package}/locale/Locale_LocaleLanguageCountry.java[tag=code]
----
-. Um `Locale` pode ter ainda uma Variante, um Script e Extensões.
+. A `Locale` can also have a Variant, a Script and Extensions.
+
[source,java,indent=0]
.{java-package}/locale/Locale_VarScriptExtension.java
@@ -79,9 +77,9 @@ include::{section-java-package}/locale/Locale_LocaleLanguageCountry.java[tag=cod
include::{section-java-package}/locale/Locale_VarScriptExtension.java[tag=code]
----
+
-TIP: No exame da certificação, a Oracle geralmente só utiliza idioma e país.
+TIP: In the certification exam, Oracle usually only uses language and country.
-. É possível construir um Locale com o `Builder`, com construtores, ou por uma _Language Tag_.
+. It is possible to build a Locale with `Builder`, with constructors, or by a _Language Tag_.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleInstantiation.java
@@ -89,13 +87,13 @@ TIP: No exame da certificação, a Oracle geralmente só utiliza idioma e país.
include::{section-java-package}/locale/Locale_LocaleInstantiation.java[tag=code]
----
+
-A diferença entre eles é:
+The difference between them is:
+
-* Com os construtores é possível passar apenas o idioma, a região (país) e uma variante.
-* Com language tags é possível passar uma `String` no padrão https://en.wikipedia.org/wiki/IETF_language_tag[IETF BCP 47].
-* Com o builder é possível criar da forma mais específica possível: idioma, região, variante, script e extensões.
+* With constructors it is possible to pass only the language, the region (country) and a variant.
+* With language tags you can pass a `String` in the pattern https://en.wikipedia.org/wiki/IETF_language_tag[IETF BCP 47].
+* With the builder you can create as specific as possible: language, region, variant, script and extensions.
-. O `Locale` aceita letras maiúsculas e minúsculas escritas de forma incorreta.
+. `Locale` accepts incorrectly typed uppercase and lowercase letters.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleCase.java
@@ -103,7 +101,7 @@ A diferença entre eles é:
include::{section-java-package}/locale/Locale_LocaleCase.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR
@@ -111,14 +109,15 @@ pt_BR
pt_BR
----
+
-Nesse exemplo, escrevemos de forma *incorreta*:
+In this example, we wrote *incorrectly*:
+
-* O idioma deveria ser minúsculo (pt), mas está maiúsculo (PT).
-* A região deveria estar maiúscula (BR), está minúscula (br).
+* Language should be lowercase (pt), but it is in uppercase (PT).
+* Region should be uppercase (BR), but it is in lowercase (br).
+
+
-Mesmo assim, o `Locale` é criado corretamente. Veja que isso é um código *ruim*. O ideal é sempre escrever respeitando maiúsculas e minúsculas.
+Even so, `Locale` is created correctly. Note that this is *bad* code. The ideal is always to write respecting the case.
-. Existem algumas constantes na classe `Locale` para as localizações mais populares.
+. There are some constants in the `Locale` class for the most popular locations.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleCommons.java
@@ -126,7 +125,7 @@ Mesmo assim, o `Locale` é criado corretamente. Veja que isso é um código *rui
include::{section-java-package}/locale/Locale_LocaleCommons.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
en_CA
@@ -139,7 +138,7 @@ zh_CN
zh_TW
----
-. É possível recuperar o `Locale` padrão ou alterá-lo programaticamente.
+. You can retrieve the default `Locale` or change it programmatically.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleDefault.java
@@ -147,14 +146,14 @@ zh_TW
include::{section-java-package}/locale/Locale_LocaleDefault.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-pt_BR
+en_BR
ko_KR
----
-. É possível verificar os `Locale` disponíveis, pois eles variam de acordo com a JVM sendo executada.
+. You can check the available `Locale` as they vary according to the JVM running.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleAvailable.java
@@ -162,22 +161,21 @@ ko_KR
include::{section-java-package}/locale/Locale_LocaleAvailable.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-
-nn
+ar_AE
ar_JO
+ar_SY
+hr_HR
+fr_BE
+es_PA
+mt_MT
+es_VE
bg
-kea
-nds
-zu
-am_ET
-fr_DZ
-ti_ET
----
-. Um `Locale` também pode ser representado somente pelo idioma.
+. A `Locale` can also be represented by language only.
+
[source,java,indent=0]
.{java-package}/locale/Locale_LocaleLanguageOnly.java
@@ -185,7 +183,7 @@ ti_ET
include::{section-java-package}/locale/Locale_LocaleLanguageOnly.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt
@@ -194,12 +192,12 @@ es
fr
----
-.Referências
+.References
****
* Adding Internationalization and Localization
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 255). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 255). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-localization[Internationalization and Localization in Java 8.]
@@ -209,4 +207,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* http://www.oracle.com/us/technologies/java/locale-140624.html[Internationalization: Understanding Locale in the Java Platform.]
-****
\ No newline at end of file
+****
diff --git a/book/03-localization/sections/02-resource-bundle.asc b/book/03-localization/sections/02-resource-bundle.asc
index aa17b25..69c7bdb 100644
--- a/book/03-localization/sections/02-resource-bundle.asc
+++ b/book/03-localization/sections/02-resource-bundle.asc
@@ -2,20 +2,18 @@
:section-java-package: ../../../{java-package}
:resource-package: ../../../resources
-=== Pacote de Recursos (Resource Bundle)
+=== Resource Bundle
-.Objetivo
+.Objective
--------------------------------------------------
Build a resource bundle for a locale and call a resource bundle from an application.
--
-Construa um resource bundle (conjunto de recursos) para um Locale e invoque um resource bundle a partir de uma aplicação.
--------------------------------------------------
-É esperado que o candidato saiba compreender e analisar o uso de _resource bundles_ e sua relação com a classe `Locale`.
+The candidate is expected to understand and analyze the use of _resource bundles_ and its relationship to the `Locale` class.
-Ao codificar uma aplicação com internacionalização é comum o uso de _resource bundles_, ou "conjunto de recursos" em português. São arquivos, geralmente `.properties` ou classes Java, que armazenam _Strings_. Cada arquivo contém _Strings_ em idiomas, ou _Locales_, diferentes.
+When coding an internationalized application, it is common to use _resource bundles_. These are files, usually `.properties` or Java classes, that store _Strings_. Each file contains different language _Strings_, or _Locales_.
-Antes de continuar, entenda a execução do método `main` no exemplo a seguir e o que é apresentado no console após sua execução.
+Before proceeding, understand the execution of the `main` method in the following example and what is presented on the console after its execution.
[source,java,indent=0]
.{java-package}/resourcebundle/ResourceBundle_Complete.java
@@ -51,8 +49,7 @@ include::{resource-package}/Text_es_ES.properties[]
.Saída no console
[source,console]
----
-
- -- Locale padrão (en_US) --
+ -- Default Locale (en_US) --
tripod - tripod
keyboard - keyboard
glass - glass
@@ -83,23 +80,23 @@ pen - caneta
sticker - sticker
----
-. O nome do `Locale` é o sufixo do nome do arquivo, e o _resource bundle_ padrão não tem sufixo. Exemplos:
-* `Text.properties` -> Locale padrão
+. The name of `Locale` is the filename suffix, and the default _resource bundle_ has no suffix. Examples:
+* `Text.properties` -> Default Locale
* `Text_pt_BR.properties` -> Locale `pt_BR`
* `Text_pt.properties` -> Locale `pt`
-* `Text_es_ES.properties` -> Locale `es_ES`
+* `Text_es_ES.properties` -> Locale `es_ES`
* `Text_es.properties` -> Locale `es`
-. O arquivo `.properties` pode ser expresso com 3 separadores diferentes: `=` (igual), `:` (dois pontos) ou um espaço em branco.
+. The `.properties` file can be expressed with 3 different separators: `=` (equal), `:` (colon) or a blank space.
+
.{resource-package}/Text.properties
----
include::{resource-package}/Text.properties[]
----
+
-O mais comum é utilizar o `=` para separar as propriedades, mas as 3 funcionam da mesma forma.
+The most common is using `=` to separate properties, but all 3 work the same way.
-. Em arquivos `.properties`, linhas que começam com `#` ou `!` são comentários.
+. In `.properties` files, lines that start with `#` or `!` are comments.
+
.{resource-package}/Text_pt_BR.properties
----
@@ -111,34 +108,34 @@ include::{resource-package}/Text_pt_BR.properties[]
include::{resource-package}/Text_es_ES.properties[]
----
-. Em arquivos `.properties`, apenas espaços no final da linha são considerados.
+. In `.properties` files, only spaces at the end of the line are considered.
+
.{resource-package}/Text_pt.properties
----
include::{resource-package}/Text_pt.properties[]
----
+
-Neste exemplo, não é possível ver, mas existem 3 espaços no final da linha. O resultado é o mesmo que escrever `paper=papel{sp}{sp}{sp}`.
+In this example, you cannot see, but there are 3 spaces at the end of the line. The result is the same as writing `paper=paper\{sp}\{sp}\{sp}`.
-. Em arquivos `.properties`, se você terminar a linha com uma contrabarra, pode quebrar a linha.
+. In `.properties` files, if you end the line with a backslash, you can break the line.
+
.{resource-package}/Text_es.properties
----
include::{resource-package}/Text_es.properties[]
----
+
-Neste exemplo, seria o mesmo que escrever em uma única linha: `keyboard=teclado`.
+In this example, it would be the same as typing on a single line: `keyboard=teclado`.
-. Em arquivos `.properties`, você também pode usar os caracteres java como `\t` e `\n`.
+. In `.properties` files, you can also use Java characters such as `\t` and `\n`.
+
.{resource-package}/Text_es_ES.properties
----
include::{resource-package}/Text_es_ES.properties[]
----
+
-Neste exemplo, existe uma tabulação antes da palavra `vaso`. Você pode perceber no primeiro exemplo deste capítulo que a palavra `vaso` foi impressa no console com uma tabulação à esquerda.
+In this example, there is a tab before the word `vaso`. You can see in the first example of this chapter that the word `vaso` was printed on the console with a left tab.
-. Você pode recuperar todas as chaves e valores do _resource bundle_ programaticamente.
+. You can retrieve all _resource bundle_ keys and values programmatically.
+
[source,java,indent=0]
.{java-package}/resourcebundle/ResourceBundle_KeysProgrammatically.java
@@ -146,7 +143,7 @@ Neste exemplo, existe uma tabulação antes da palavra `vaso`. Você pode perceb
include::{section-java-package}/resourcebundle/ResourceBundle_KeysProgrammatically.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
tripod - tripod
@@ -159,7 +156,7 @@ pen - caneta
sticker - sticker
----
-. O _resource bundle_ também pode ser uma classe Java.
+. The _resource bundle_ can also be a Java class.
+
[source,java,indent=0]
.resource/Text_fr_CA.java
@@ -173,13 +170,13 @@ include::{resource-package}/Text_fr_CA.java[]
include::{section-java-package}/resourcebundle/ResourceBundle_JavaBundle.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
verre
----
-. Ao utilizar classes Java, uma vantagem é poder armazenar valores que não sejam apenas `String`.
+. When using Java classes, one advantage is that you can store values other than `String`.
+
[source,java,indent=0]
.resource/Text_fr_FR.java
@@ -187,11 +184,11 @@ verre
include::{resource-package}/Text_fr_FR.java[]
----
-. A nomenclatura do arquivo é a mesma para classes Java e arquivos `.properties`, mudando apenas a extensão.
+. The file nomenclature is the same for Java classes and `.properties` files, changing only the extension.
+
-Veja que os arquivos `.properties` se chamam `Text_xx_XX.properties`, e os arquivos `.java` se chamam `Text_xx_XX.java`. Programaticamente, ambos são utilizados da mesma forma.
+Note that the `.properties` files are named `Text_xx_XX.properties`, and the `.java` files are named `Text_xx_XX.java`. Programmatically, both are used in the same way.
-. Se houver um arquivo `.properties` e uma classe Java para o mesmo `Locale`, a classe Java é utilizada.
+. If there is a `.properties` file and a Java class for the same `Locale`, the Java class is used.
+
[source,java,indent=0]
.resource/Text_fr_CA.java
@@ -211,7 +208,7 @@ include::{resource-package}/Text_fr_CA.properties[]
include::{section-java-package}/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
stylo
@@ -219,22 +216,22 @@ verre
clavier
----
+
-Veja que os valores apresentados no console são aqueles definidos no arquivo `Text_fr_CA.java`, mostrando que a classe Java tem precedência sobre um arquivo `.properties` para o mesmo `Locale`.
+Note that the values presented in the console are those defined in the `Text_fr_CA.java` file, showing that the Java class takes precedence over a `.properties` file for the same `Locale`.
-. Ao buscar por um _resource bundle_, o Java tenta encontrar um arquivo com o `Locale` exato. Se não encontrar, busca na seguinte ordem:
-.. Um arquivo do mesmo idioma, mas sem o país;
-.. Um arquivo do `Locale` padrão;
-.. Um arquivo do `Locale` padrão, mas sem o país;
-.. Um arquivo sem `Locale`, que é o _resource bundle_ padrão;
-.. Lança `MissingResourceException` caso não encontre.
+. When searching for a _resource bundle_, Java tries to find a file with the exact `Locale`. If not find, search in the following order:
+.. A file of the same language, but without the country;
+.. A file from the default `Locale`;
+.. A standard `Locale` file, but without the country;
+.. A file without `Locale`, which is the default _resource bundle_;
+.. Throws `MissingResourceException` if not found.
+
-Por exemplo, ao executar a aplicação com o Locale padrão `en_US`, e solicitar um Locale `pt_BR`, a ordem de busca do _resource bundle_ seria a seguinte:
+For example, when running the application with the default Locale `en_US`, and requesting a Locale `pt_BR`, the _resource bundle_ search order would be as follows:
+
-... `Text_pt_BR` -> Locale exato
-... `Text_pt` -> Locale solicitado, sem o país
-... `Text_en_US` -> Locale padrão
-... `Text_en` -> Locale padrão, sem o país
-... `Text` -> _Resource Bundle_ padrão
+... `Text_pt_BR` -> Exact Locale
+... `Text_pt` -> Requested Locale, without country
+... `Text_en_US` -> Default Locale
+... `Text_en` -> Default Locale, without country
+... `Text` -> _Resource Default Bundle_
+
[source,java,indent=0]
.{java-package}/resourcebundle/ResourceBundle_NotExactLocale.java
@@ -249,11 +246,11 @@ pt_BR
it
----
+
-Veja que o `Locale` padrão é `pt_BR`. Por isso ele foi utilizado ao solicitar um _resource bundle_ para `zh_CN`, pois não existe um bundle para esse `Locale`.
+Note that the default `Locale` is `pt_BR`. So it was used when requesting a _resource bundle_ for `zh_CN`, as there is no bundle for this `Locale`.
+
-Por outro lado, ao solicitar um _resource bundle_ para o `Locale` `it_CH`, ele encontrou o mais próximo, que seria o `Locale` `it`, mas sem um país específico.
+On the other hand, when requesting a _resource bundle_ for `Locale` `it_CH`, he found the closest one, which would be `Locale` `it`, but without a specific country.
-. Os arquivos mais específicos herdam as chaves e valores de arquivos mais genéricos, caso eles não as tenham.
+. More specific files inherit keys and values from more generic files if they do not have them.
+
[source,java,indent=0]
.{java-package}/resourcebundle/ResourceBundle_Inheritance.java
@@ -276,7 +273,7 @@ include::{resource-package}/Text_pt.properties[]
include::{resource-package}/Text_pt_BR.properties[]
----
+
-.Saída no console
+.console output
[source,console]
----
Locale: pt_BR
@@ -285,18 +282,18 @@ papel
keyboard
----
+
-Veja que nesse exemplo foi localizado um _resource bundle_ com o `Locale` exato `pt_BR`. Porém, nem todas as chaves foram encontradas nesse arquivo:
+Note that in this example a _resource bundle_ with the exact `pt_BR` `Locale` was found. However, not all keys were found in this file:
+
-* `caneta` foi localizado no arquivo `Text_pt_BR.properties`
-* `papel` foi localizado no arquivo `Text_pt.properties`
-* `keyboard` foi localizado no arquivo `Text.properties`
+* `pen` was found in the `Text_pt_BR.properties` file
+* `paper` was found in the `Text_pt.properties` file
+* `keyboard` was found in the `Text.properties` file
-.Referências
+.References
****
* Using a Resource Bundle
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 258). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 258). Wiley. Kindle Edition.
* https://www.baeldung.com/java-resourcebundle[A Guide to the ResourceBundle.]
@@ -304,4 +301,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html[About the ResourceBundle Class.] Java Documentation.
-****
\ No newline at end of file
+****
diff --git a/book/03-localization/sections/03-date-time.asc b/book/03-localization/sections/03-date-time.asc
index d6f9b19..dd65597 100644
--- a/book/03-localization/sections/03-date-time.asc
+++ b/book/03-localization/sections/03-date-time.asc
@@ -1,37 +1,35 @@
:java-package: src/org/j6toj8/localization
:section-java-package: ../../../{java-package}
-=== Data e Hora
+=== Date and Time
-.Objetivo
+.Objective
--------------------------------------------------
Create and manage date- and time-based events by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration, including a combination of date and time in a single object.
--
-Crie e gerencie eventos baseados em data e hora utilizando LocalDate, LocalTime, LocalDateTime, Instant, Period, e Duration, incluindo combinação de data e hora em um único objeto.
--------------------------------------------------
-O Java 8 possui uma forma totalmente nova de lidar com data e hora. Várias classes novas foram introduzidas no pacote `java.time.*`. Vejamos a seguir alguns exemplos no formado ISO-8601.
+Java 8 has a whole new way of dealing with date and time. Several new classes have been introduced in the `java.time.*` Package. Here are some examples in the ISO-8601 format.
-* `LocalDate` -> Data sem fuso horário, como `2007-12-03`.
-* `LocalTime` -> Hora sem fuso horário, como `10:15:30.125`.
-* `LocalDateTime` -> Uma data com hora sem fuso horário, como `2007-12-03T10:15:30.125`.
-* `ZonedDateTime` -> Uma data com hora e com fuso horário, como `2007-12-03T10:15:30.125+01:00 Europe/Paris`.
-* `Instant` -> Um ponto na linha do tempo, um instante.
-* `Period` -> Uma quantidade de tempo baseado em data, como "2 anos, 3 meses and 4 dias".
-* `Duration` -> Uma quantidade de tempo baseado em hora, como "34,5 segundos".
+* `LocalDate` -> Date without time zone, such as `2007-12-03`.
+* `LocalTime` -> Time without time zone, such as `10:15:30.125`.
+* `LocalDateTime` -> A time date without a time zone, such as `2007-12-03T10:15:30.125`.
+* `ZonedDateTime` -> A date with time and time zone, such as `2007-12-03T10:15:30.125+01:00 Europe/Paris`.
+* `Instant` -> A point on the timeline, an instant.
+* `Period` -> A date-based amount of time, such as "2 years, 3 months and 4 days".
+* `Duration` -> A time-based amount of time, such as "34.5 seconds".
-Essas novas classes foram melhor projetadas para lidar com os conceitos de data, hora e tempo. As classes antigas, `java.util.Date` e `java.util.Calendar`, não caem na prova de certificação.
+These new classes are best designed to handle the concepts of date, hour, and time. The old classes `java.util.Date` and `java.util.Calendar` won't be requested on the certification test.
-Quase todas essas classes serão apresentadas nessa seção. A única exceção é `ZonedDateTime`, que será apresentada na seção de fusos horários e horário de verão.
+Almost all of these classes will be presented in this section. The only exception is `ZonedDateTime`, which will be featured in the time zone and daylight saving time section.
-Todas as novas classes são https://pt.wikipedia.org/wiki/Objeto_imut%C3%A1vel[imutáveis] e https://pt.wikipedia.org/wiki/Thread_safety[_thread safe_]. Ou seja, não é necessário se preocupar com concorrência.
+All new classes are https://en.wikipedia.org/wiki/Immutable_object[immutable] and https://en.wikipedia.org/wiki/Thread_safety[thread safe]. That is, there is no need to worry about concurrency.
==== LocalDate
-Um `LocalDate` representa uma data sem fuso horário, como `2007-12-03`.
+A `LocalDate` represents a date without a time zone, such as `2007-12-03`.
-. A prova geralmente irá utilizar datas no formato americano: `mes/dia/ano`.
-. É possível criar um `LocalDate` através do método `static` chamado `now`.
+. The test will usually use dates in the US format: `month/day/year`.
+. You can create a `LocalDate` using the `static` method called `now`.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Now.java
@@ -39,17 +37,17 @@ Um `LocalDate` representa uma data sem fuso horário, como `2007-12-03`.
include::{section-java-package}/datetime/localdate/LocalDate_Now.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20
----
+
-A saída no console irá apresentar a data atual.
+The console output will display the current date.
-. Também é possível criar um `LocalDate` através do método `static` chamado `of`.
-. Você pode utilizar o `enum` `Month` ou um `int` para representar o mês.
-. Diferente das APIs antigas do Java, o mês agora começa no número `1`, que é Janeiro.
+. It is also possible to create a `LocalDate` through the `static` method called `of`.
+. You can use `Month` `enum` or an `int` to represent the month.
+. Unlike older Java APIs, the month now starts at the number `1`, which is January.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Of.java
@@ -57,14 +55,14 @@ A saída no console irá apresentar a data atual.
include::{section-java-package}/datetime/localdate/LocalDate_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20
2019-05-20
----
-. Assim como todas a novas classes de data e hora, não é possível criar uma instância de `LocalDate` utilizando o construtor.
+. As with all new datetime classes, it is not possible to create an instance of `LocalDate` using the constructor.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Constructor.java
@@ -72,7 +70,7 @@ include::{section-java-package}/datetime/localdate/LocalDate_Of.java[tag=code]
include::{section-java-package}/datetime/localdate/LocalDate_Constructor.java[tag=code]
----
-. Será lançada a exceção `DateTimeException` ao tentar criar uma data inválida.
+. The `DateTimeException` exception will be thrown when trying to create an invalid date.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Invalid.java
@@ -80,7 +78,7 @@ include::{section-java-package}/datetime/localdate/LocalDate_Constructor.java[ta
include::{section-java-package}/datetime/localdate/LocalDate_Invalid.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 33
@@ -90,7 +88,7 @@ Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfM
at org.j6toj8.localization.datetime.localdate.LocalDate_Invalid.main(LocalDate_Invalid.java:10)
----
-. Existem vários métodos para somar e subtrair de `LocalDate`.
+. There are several methods for adding and subtracting from `LocalDate`.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Manipulate.java
@@ -98,24 +96,23 @@ Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfM
include::{section-java-package}/datetime/localdate/LocalDate_Manipulate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20
-+2 dias: 2019-05-22
-+2 semanas: 2019-06-03
-+2 meses: 2019-07-20
-+2 anos: 2021-05-20
-+2 anos: 2021-05-20
-+2 décadas: 2039-05-20
--2 dias: 2019-05-18
--2 semanas: 2019-05-06
--2 meses: 2019-03-20
--2 anos: 2017-05-20
--2 décadas: 1999-05-20
++2 days: 2019-05-22
++2 weeks: 2019-06-03
++2 months: 2019-07-20
++2 years: 2021-05-20
++2 decades: 2039-05-20
+-2 days: 2019-05-18
+-2 weeks: 2019-05-06
+-2 months: 2019-03-20
+-2 years: 2017-05-20
+-2 decades: 1999-05-20
----
-. `LocalDate` é imutável, então é necessário armazenar o retorno de uma alteração em uma variável.
+. `LocalDate` is immutable, so you must store the return of a change in a variable.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Immutability.java
@@ -123,7 +120,7 @@ include::{section-java-package}/datetime/localdate/LocalDate_Manipulate.java[tag
include::{section-java-package}/datetime/localdate/LocalDate_Immutability.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20
@@ -131,7 +128,7 @@ include::{section-java-package}/datetime/localdate/LocalDate_Immutability.java[t
2019-05-21
----
-. É comum utilizar o encadeamento de chamadas com esses métodos.
+. It is common to use call chaining with these methods.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_Chaining.java
@@ -139,14 +136,14 @@ include::{section-java-package}/datetime/localdate/LocalDate_Immutability.java[t
include::{section-java-package}/datetime/localdate/LocalDate_Chaining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20
2020-06-21
----
-. Ao manipular a data, o `LocalDate` irá manipular os meses e anos conforme necessário.
+. When handling the date, `LocalDate` will handle the months and years as needed.
+
[source,java,indent=0]
.{java-package}/datetime/localdate/LocalDate_AdjustDifferentUnit.java
@@ -154,7 +151,7 @@ include::{section-java-package}/datetime/localdate/LocalDate_Chaining.java[tag=c
include::{section-java-package}/datetime/localdate/LocalDate_AdjustDifferentUnit.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-11-30
@@ -165,10 +162,10 @@ include::{section-java-package}/datetime/localdate/LocalDate_AdjustDifferentUnit
==== LocalTime
-Um `LocalTime` representa uma hora sem fuso horário e sem data, como `10:15:30.125`.
+A `LocalTime` represents a time with no time zone and no date, such as `10:15:30.125`.
-. A hora é representada no formato `hora:minuto:segundo.nano`.
-. É possível criar um `LocalTime` através do método `static` chamado `now`.
+. The time is represented in the format `hour:minute:second.nano`.
+. You can create a `LocalTime` using the `static` method called `now`.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Now.java
@@ -176,15 +173,15 @@ Um `LocalTime` representa uma hora sem fuso horário e sem data, como `10:15:30.
include::{section-java-package}/datetime/localtime/LocalTime_Now.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:15:23.197
----
+
-A saída no console irá apresentar a hora atual.
+The console output will display the current time.
-. Também é possível criar um `LocalTime` através do método `static` chamado `of`.
+. It is also possible to create a `LocalTime` through the `static` method called `of`.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Of.java
@@ -192,7 +189,7 @@ A saída no console irá apresentar a hora atual.
include::{section-java-package}/datetime/localtime/LocalTime_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:20:01.135
@@ -201,7 +198,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Of.java[tag=code]
09:20
----
-. Assim como todas a novas classes de data e hora, não é possível criar uma instância de `LocalTime` utilizando o construtor.
+. As with all new date and time classes, it is not possible to create an instance of `LocalTime` using the constructor.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Constructor.java
@@ -209,7 +206,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Of.java[tag=code]
include::{section-java-package}/datetime/localtime/LocalTime_Constructor.java[tag=code]
----
-. Será lançada a exceção `DateTimeException` ao tentar criar uma hora inválida.
+. The `DateTimeException` exception will be thrown when trying to create an invalid time.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Invalid.java
@@ -217,7 +214,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Constructor.java[ta
include::{section-java-package}/datetime/localtime/LocalTime_Invalid.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Exception in thread "main" java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 - 23): 24
@@ -227,7 +224,7 @@ Exception in thread "main" java.time.DateTimeException: Invalid value for HourOf
at org.j6toj8.localization.datetime.localtime.LocalTime_Invalid.main(LocalTime_Invalid.java:9)
----
-. Existem vários métodos para somar e subtrair de `LocalTime`.
+. There are several methods for adding and subtracting from `LocalTime`.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Manipulate.java
@@ -235,25 +232,25 @@ Exception in thread "main" java.time.DateTimeException: Invalid value for HourOf
include::{section-java-package}/datetime/localtime/LocalTime_Manipulate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:26:12
-+2 horas: 11:26:12
-+2 minutos: 09:28:12
-+2 segundos: 09:26:14
-+2 nanosegundos: 09:26:12.000000002
-+2 microssegundos: 09:26:12.000002
-+2 milissegundos: 09:26:12.002
--2 horas: 07:26:12
--2 minutos: 09:24:12
--2 segundos: 09:26:10
--2 nanosegundos: 09:26:11.999999998
--2 microssegundos: 09:26:11.999998
--2 milissegundos: 09:26:11.998
++2 hours: 11:26:12
++2 minutes: 09:28:12
++2 seconds: 09:26:14
++2 nanoseconds: 09:26:12.000000002
++2 microseconds: 09:26:12.000002
++2 milliseconds: 09:26:12.002
+-2 hours: 07:26:12
+-2 minutes: 09:24:12
+-2 seconds: 09:26:10
+-2 nanoseconds: 09:26:11.999999998
+-2 microseconds: 09:26:11.999998
+-2 milliseconds 09:26:11.998
----
-. `LocalTime` é imutável, então é necessário armazenar o retorno de uma alteração em uma variável.
+. `LocalTime` is immutable, so you must store the return of a change in a variable.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Immutability.java
@@ -261,7 +258,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Manipulate.java[tag
include::{section-java-package}/datetime/localtime/LocalTime_Immutability.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:31:05
@@ -269,7 +266,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Immutability.java[t
10:31:05
----
-. É comum utilizar o encadeamento de chamadas com esses métodos.
+. It is common to use call chaining with these methods.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_Chaining.java
@@ -277,14 +274,14 @@ include::{section-java-package}/datetime/localtime/LocalTime_Immutability.java[t
include::{section-java-package}/datetime/localtime/LocalTime_Chaining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:32:05
10:33:06.001
----
-. Ao manipular a hora, o `LocalTime` irá manipular as horas, minutos e segundos conforme necessário.
+. When handling the time, `LocalTime` will handle the hours, minutes and seconds as needed.
+
[source,java,indent=0]
.{java-package}/datetime/localtime/LocalTime_AdjustDifferentUnit.java
@@ -292,7 +289,7 @@ include::{section-java-package}/datetime/localtime/LocalTime_Chaining.java[tag=c
include::{section-java-package}/datetime/localtime/LocalTime_AdjustDifferentUnit.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
09:59:59
@@ -304,12 +301,12 @@ include::{section-java-package}/datetime/localtime/LocalTime_AdjustDifferentUnit
==== LocalDateTime
-Um `LocalDateTime` representa uma data com hora, mas sem fuso horário, como `2007-12-03T10:15:30.125`.
+A `LocalDateTime` represents a date with time, but no time zone, such as `2007-12-03T10:15:30.125`.
-As regras para o `LocalDateTime` são basicamente a junção daquelas para `LocalDate` e `LocalTime`.
+The rules for `LocalDateTime` are basically the merging of those for `LocalDate` and `LocalTime`.
-. O `LocalDateTime` é apresentado no formato `ano-mes-diaThora:minuto:segundo.nano`.
-. É possível criar um `LocalDateTime` através do método `static` chamado `now`.
+. The `LocalDateTime` is displayed in the format `year-month-dayThour:minute:second.nano`.
+. You can create a `LocalDateTime` using the `static` method called `now`.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Now.java
@@ -317,15 +314,15 @@ As regras para o `LocalDateTime` são basicamente a junção daquelas para `Loca
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Now.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-24T10:13:58.370
----
+
-A saída no console irá apresentar a data e hora atual.
+The console output will display the current date and time.
-. Também é possível criar um `LocalDateTime` através do método `static` chamado `of`.
+. It is also possible to create a `LocalDateTime` through the `static` method called `of`.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Of.java
@@ -333,7 +330,7 @@ A saída no console irá apresentar a data e hora atual.
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20:12
@@ -345,7 +342,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Of.java[tag
2019-05-20T09:20:12.000000135
----
-. Assim como todas a novas classes de data e hora, não é possível criar uma instância de `LocalDateTime` utilizando o construtor.
+. As with all new date and time classes, you cannot create an instance of `LocalDateTime` using the constructor.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Constructor.java
@@ -353,7 +350,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Of.java[tag
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Constructor.java[tag=code]
----
-. Será lançada a exceção `DateTimeException` ao tentar criar uma data ou hora inválida.
+. The `DateTimeException` exception will be thrown when trying to create an invalid date or time.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Invalid.java
@@ -361,7 +358,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Constructor
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Invalid.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
@@ -371,7 +368,7 @@ Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
at org.j6toj8.localization.datetime.localdatetime.LocalDateTime_Invalid.main(LocalDateTime_Invalid.java:10)
----
-. Existem vários métodos para somar e subtrair de `LocalDateTime`. São basicamente todos os disponíveis para `LocalDate` e `LocalTime`.
+. There are several methods for adding and subtracting from `LocalDateTime`. These are basically all available for `LocalDate` and `LocalTime`.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Manipulate.java
@@ -379,36 +376,35 @@ Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Manipulate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20:12
-+2 horas: 2019-05-20T11:20:12
-+2 minutos: 2019-05-20T09:22:12
-+2 segundos: 2019-05-20T09:20:14
-+2 nanosegundos: 2019-05-20T09:20:12.000000002
-+2 microssegundos: 2019-05-20T09:20:12.000002
-+2 milissegundos: 2019-05-20T09:20:12.002
--2 horas: 2019-05-20T07:20:12
--2 minutos: 2019-05-20T09:18:12
--2 segundos: 2019-05-20T09:20:10
--2 nanosegundos: 2019-05-20T09:20:11.999999998
--2 microssegundos: 2019-05-20T09:20:11.999998
--2 milissegundos: 2019-05-20T09:20:11.998
-+2 dias: 2019-05-22T09:20:12
-+2 semanas: 2019-06-03T09:20:12
-+2 meses: 2019-07-20T09:20:12
-+2 anos: 2021-05-20T09:20:12
-+2 anos: 2021-05-20T09:20:12
-+2 décadas: 2039-05-20T09:20:12
--2 dias: 2019-05-18T09:20:12
--2 semanas: 2019-05-06T09:20:12
--2 meses: 2019-03-20T09:20:12
--2 anos: 2017-05-20T09:20:12
--2 décadas: 1999-05-20T09:20:12
-----
-
-. `LocalDateTime` é imutável, então é necessário armazenar o retorno de uma alteração em uma variável.
++2 hours: 2019-05-20T11:20:12
++2 minutes: 2019-05-20T09:22:12
++2 seconds: 2019-05-20T09:20:14
++2 nanoseconds: 2019-05-20T09:20:12.000000002
++2 microseconds: 2019-05-20T09:20:12.000002
++2 milliseconds: 2019-05-20T09:20:12.002
+-2 hours: 2019-05-20T07:20:12
+-2 minutes: 2019-05-20T09:18:12
+-2 seconds: 2019-05-20T09:20:10
+-2 nanoseconds: 2019-05-20T09:20:11.999999998
+-2 microseconds: 2019-05-20T09:20:11.999998
+-2 milliseconds: 2019-05-20T09:20:11.998
++2 days: 2019-05-22T09:20:12
++2 weeks: 2019-06-03T09:20:12
++2 months: 2019-07-20T09:20:12
++2 years: 2021-05-20T09:20:12
++2 decades: 2039-05-20T09:20:12
+-2 days: 2019-05-18T09:20:12
+-2 weeks: 2019-05-06T09:20:12
+-2 months: 2019-03-20T09:20:12
+-2 years: 2017-05-20T09:20:12
+-2 decades: 1999-05-20T09:20:12
+----
+
+. `LocalDateTime` is immutable, so you must store the return of a change in a variable.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Immutability.java
@@ -416,7 +412,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Manipulate.
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Immutability.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20
@@ -424,7 +420,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Immutabilit
2019-05-20T10:20
----
-. É comum utilizar o encadeamento de chamadas com esses métodos.
+. It is common to use call chaining with these methods.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_Chaining.java
@@ -432,14 +428,14 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Immutabilit
include::{section-java-package}/datetime/localdatetime/LocalDateTime_Chaining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20
2020-05-21T10:20
----
-. Ao manipular a data ou hora, o `LocalDateTime` irá manipular os outros campos conforme necessário.
+. When handling the date or time, `LocalDateTime` will handle the other fields as needed.
+
[source,java,indent=0]
.{java-package}/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java
@@ -447,7 +443,7 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_Chaining.ja
include::{section-java-package}/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-12-31T23:59:59
@@ -456,12 +452,12 @@ include::{section-java-package}/datetime/localdatetime/LocalDateTime_AdjustDiffe
==== Instant
-Um `Instant` representa um momento na linha do tempo, no fuso horário do https://pt.wikipedia.org/wiki/Tempo_Universal_Coordenado[UTC] (às vezes chamado de https://pt.wikipedia.org/wiki/Tempo_M%C3%A9dio_de_Greenwich[GMT]), como `2007-12-03T10:15:30.125Z`.
+An `Instant` represents a moment on the timeline in the https://en.wikipedia.org/wiki/Coordinated_Universal_Time[UTC] time zone (sometimes called https://en.wikipedia.org/wiki/Greenwich_Mean_Time[GMT]), such as `2007-12-03T10:15:30.125Z`.
-O `Instant` difere de todos os tipos apresentados anteriormente, pois possui um fuso horário (UTC) e representa o mesmo momento na linha do tempo em qualquer lugar do mundo.
+`Instant` differs from all of the types presented earlier in that it has a time zone (UTC) and represents the same moment on the timeline anywhere in the world.
-. O `Instant` é apresentado no formato `ano-mes-diaThora:minuto:segundo.nanoZ`.
-. É possível criar um `Instant` através do método `static` chamado `now`.
+. `Instant` is presented in the format `year-month-dayThour:minute:second.nanoZ`.
+. You can create an `Instant` using the `static` method called `now`.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Now.java
@@ -469,15 +465,15 @@ O `Instant` difere de todos os tipos apresentados anteriormente, pois possui um
include::{section-java-package}/datetime/instant/Instant_Now.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-27T21:13:10.450Z
----
+
-A saída no console irá apresentar a data e hora atual no fuso horário UTC.
+The console output will display the current date and time in the UTC time zone.
-. Também é possível criar um `Instant` através dos métodos `static` chamados `ofEpochMilli` ou `ofEpochSecond`. O parâmetro é a quantidade de milissegundos, ou segundos, desde `1970-01-01T00:00:00Z`.
+. It is also possible to create an `Instant` using `static` methods called `ofEpochMilli` or `ofEpochSecond`. The parameter is the number of milliseconds, or seconds, since `1970-01-01T00:00:00Z`.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Of.java
@@ -485,7 +481,7 @@ A saída no console irá apresentar a data e hora atual no fuso horário UTC.
include::{section-java-package}/datetime/instant/Instant_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2001-09-09T01:46:40Z
@@ -493,7 +489,7 @@ include::{section-java-package}/datetime/instant/Instant_Of.java[tag=code]
2001-09-09T01:46:40.123Z
----
-. Assim como todas a novas classes de data e hora, não é possível criar uma instância de `Instant` utilizando o construtor.
+. As with all new date and time classes, it is not possible to create an instance of `Instant` using the builder.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Constructor.java
@@ -501,7 +497,7 @@ include::{section-java-package}/datetime/instant/Instant_Of.java[tag=code]
include::{section-java-package}/datetime/instant/Instant_Constructor.java[tag=code]
----
-. Existem vários métodos para somar e subtrair de `Instant`. Porém, não suporta operações com unidades maiores do que dias.
+. There are several methods for adding and subtracting from `Instant`. However, it does not support operations with units larger than days.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Manipulate.java
@@ -509,27 +505,27 @@ include::{section-java-package}/datetime/instant/Instant_Constructor.java[tag=co
include::{section-java-package}/datetime/instant/Instant_Manipulate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2001-09-09T01:46:40Z
-+2 segundos: 2001-09-09T01:46:42Z
-+2 nanosegundos: 2001-09-09T01:46:40.000000002Z
-+2 microssegundos: 2001-09-09T01:46:40.000002Z
-+2 milissegundos: 2001-09-09T01:46:40.002Z
--2 segundos: 2001-09-09T01:46:38Z
--2 nanosegundos: 2001-09-09T01:46:39.999999998Z
--2 microssegundos: 2001-09-09T01:46:39.999998Z
--2 milissegundos: 2001-09-09T01:46:39.998Z
-+2 dias: 2001-09-11T01:46:40Z
++2 seconds: 2001-09-09T01:46:42Z
++2 nanoseconds: 2001-09-09T01:46:40.000000002Z
++2 microseconds: 2001-09-09T01:46:40.000002Z
++2 milliseconds: 2001-09-09T01:46:40.002Z
+-2 seconds: 2001-09-09T01:46:38Z
+-2 nanoseconds: 2001-09-09T01:46:39.999999998Z
+-2 microseconds: 2001-09-09T01:46:39.999998Z
+-2 milliseconds: 2001-09-09T01:46:39.998Z
++2 days: 2001-09-11T01:46:40Z
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Weeks
at java.time.Instant.plus(Instant.java:862)
at org.j6toj8.localization.datetime.instant.Instant_Manipulate.main(Instant_Manipulate.java:21)
----
-. `Instant` é imutável, então é necessário armazenar o retorno de uma alteração em uma variável.
-. Assim como as outras classes de data e hora, é comum utilizar o encadeamento de chamadas com esses métodos.
-. Assim como as outras classes de data e hora, ao manipular o `Instant` irá manipular os outros campos conforme necessário.
+. `Instant` is immutable, so you must store the return of a change in a variable.
+. As with other date and time classes, it is common to use call chaining with these methods.
+. As with other date and time classes, manipulating `Instant` will handle the other fields as needed.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Immutability.java
@@ -537,7 +533,7 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
include::{section-java-package}/datetime/instant/Instant_Immutability.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2001-09-09T01:46:40Z
@@ -545,7 +541,7 @@ include::{section-java-package}/datetime/instant/Instant_Immutability.java[tag=c
2001-09-09T01:47:40Z
----
-. Você pode transformar um `LocalDateTime` em um `Instant`, e vice-versa, caso informe um fuso horário, .
+. You can turn a `LocalDateTime` into an `Instant`, and vice versa if you enter a time zone.
+
[source,java,indent=0]
.{java-package}/datetime/instant/Instant_Convert.java
@@ -553,7 +549,7 @@ include::{section-java-package}/datetime/instant/Instant_Immutability.java[tag=c
include::{section-java-package}/datetime/instant/Instant_Convert.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
LocalDateTime: 2019-05-27T13:01:01
@@ -567,15 +563,15 @@ Instant: 2019-05-27T13:01:01Z
==== Period
-Um `Period` é uma quantidade de tempo baseado em datas, como anos, meses ou dias. Por exemplo: `2 anos, 3 meses e 4 dias`.
+A `Period` is an amount of time based on dates, such as years, months, or days. For example: `2 years, 3 months and 4 days`.
-. O `Period` é apresentado no formato `PxYxMxD`, onde:
-* `P` representa que é um Period.
-* `xY` é a quantidade de anos. 5 anos seria `5Y`.
-* `xM` é a quantidade de meses. 3 meses seria `3M`.
-* `xD` é a quantidade de dias. 2 dias seria `2D`.
-. Ao imprimir um `Period`, apenas os campos com valor são apresentados. Campos zerados são omitidos.
-. É possível criar um `Period` através dos métodos `static` chamados `of*`.
+. `Period` is presented in `PxYxMxD` format, where:
+* `P` represents a Period.
+* `xY` is the number of years. 5 years would be `5Y`.
+* `xM` is the number of months. 3 months would be `3M`.
+* `xD` is the number of days. 2 days would be `2D`.
+. When printing a `Period`, only fields with value are displayed. Empty fields (with zero) are omitted.
+. You can create a `Period` using `static` methods called `of *`.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_Of.java
@@ -583,7 +579,7 @@ Um `Period` é uma quantidade de tempo baseado em datas, como anos, meses ou dia
include::{section-java-package}/datetime/period/Period_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
P2D
@@ -593,9 +589,9 @@ P2Y
P2Y1M3D
----
+
-Perceba que o período de 2 semanas é apresentado como `14D`, pois `Period` não armazena semanas. O método `ofWeeks` é apenas um facilitador, onde cada semana é o equivalente a 7 dias.
+Note that the 2 week period is displayed as `14D` as `Period` does not store weeks. The `ofWeeks` method is just a facilitator, where each week is the equivalent of 7 days.
-. Também é possível criar um `Period` a partir de duas `LocalDate`.
+. It is also possible to create a `Period` from two `LocalDate`.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_Between.java
@@ -603,15 +599,15 @@ Perceba que o período de 2 semanas é apresentado como `14D`, pois `Period` nã
include::{section-java-package}/datetime/period/Period_Between.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
P28Y9M22D
----
+
-No exemplo anterior podemos ver que uma pessoa nascida no dia `6 de agosto de 1990` possuía `28 anos, 9 meses e 22 dias` de idade no dia em que esse código foi executado: `28/05/2019`.
+In the previous example we can see that a person born on `August 6, 1990` was `28 years, 9 months and 22 days` on the day this code was executed: `05/28/2019`.
-. `Period` também armazena uma quantidade de dias maior que um mês, e de meses maior que um ano.
+. `Period` also stores more than one month, and more than one year.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_BiggerValues.java
@@ -619,7 +615,7 @@ No exemplo anterior podemos ver que uma pessoa nascida no dia `6 de agosto de 19
include::{section-java-package}/datetime/period/Period_BiggerValues.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
P60M2D
@@ -627,12 +623,12 @@ P30M50D
P5Y200M1000D
----
+
-Perceba que `Period` não converteu meses em anos, ou dias em meses.
+Note that `Period` did not convert months to years, or days to months.
+
[NOTE]
-.Curiosidades!
+.Curiosities!
--
-É possível normalizar um `Period` que não está com o intervalo padrão através do método `normalized`. Mas serão considerados apenas os anos e meses, deixando os dias intactos.
+You can normalize a `Period` that is not within the default range by the `normalized` method. But only the years and months will be considered, leaving the days intact.
[source,java,indent=0]
.{java-package}/datetime/period/Period_Curiosities.java
@@ -640,7 +636,8 @@ Perceba que `Period` não converteu meses em anos, ou dias em meses.
include::{section-java-package}/datetime/period/Period_Curiosities.java[tag=code1]
----
-Também é possível trabalhar com números negativos e normaliza-los.
+It is also possible to work with negative numbers and normalize them.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_Curiosities.java
----
@@ -648,7 +645,7 @@ include::{section-java-package}/datetime/period/Period_Curiosities.java[tag=code
----
--
-. É possível somar um `Period` a um `Instant`, `LocalDate` ou `LocalDateTime`.
+. You can add a `Period` to an `Instant`, `LocalDate` or `LocalDateTime`.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_Compatibility.java
@@ -656,7 +653,7 @@ include::{section-java-package}/datetime/period/Period_Curiosities.java[tag=code
include::{section-java-package}/datetime/period/Period_Compatibility.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Period: P10D
@@ -671,7 +668,7 @@ LocalDateTime: 2018-05-27T13:01:01
LocalDateTime + Period: 2018-06-06T13:01:01
----
-. *Não* é possível somar um `Period` a um `LocalTime`, pois o primeiro representa tempo baseado em datas, e o segundo armazena apenas horários.
+. It is *not* possible to add a `Period` to a `LocalTime` since the former represents time-based on dates, and the latter only stores times.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_LocalTime.java
@@ -679,7 +676,7 @@ LocalDateTime + Period: 2018-06-06T13:01:01
include::{section-java-package}/datetime/period/Period_LocalTime.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Period: P13D
@@ -692,9 +689,9 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
at org.j6toj8.localization.datetime.period.Period_LocalTime.main(Period_LocalTime.java:15)
----
+
-Veja que ocorreu exceção ao tentar somar um `Period` a um `LocalTime`.
+Note that an exception occurred while trying to add a `Period` to a `LocalTime`.
-. *Não* é possível somar um `Period` que contém meses ou anos a um `Instant`. Como vimos na seção anterior sobre `Instant`, ele não suporta operações com valores maiores que dias.
+. It is *not* possible to add a `Period` containing months or years to an `Instant`. As we saw in the previous section on `Instant`, it does not support operations with values longer than days.
+
[source,java,indent=0]
.{java-package}/datetime/period/Period_Instant.java
@@ -702,7 +699,7 @@ Veja que ocorreu exceção ao tentar somar um `Period` a um `LocalTime`.
include::{section-java-package}/datetime/period/Period_Instant.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Period: P1M
@@ -717,15 +714,15 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
==== Duration
-Uma `Duration` é uma quantidade de tempo baseado em hora, como segundos, minutos ou horas. Por exemplo: `2 horas, 3 minutos e 4 segundos`.
+A `Duration` is a time-based amount of time, such as seconds, minutes, or hours. For example: `2 hours, 3 minutes and 4 seconds`.
-. A `Duration` é apresentada no formato `PTxHxMxS`, onde:
-* `PT` representa que é um `Duration`.
-* `xH` representa a quantidade de horas.
-* `xM` representa a quantidade de minutos.
-* `xS` representa a quantidade de segundos.
-. Assim como um `Period`, ao imprimir uma `Duration` apenas os campos com valor são apresentados. Campos zerados são omitidos.
-. É possível criar uma `Duration` através dos métodos `static` chamados `of*`.
+. The `Duration` is presented in `PTxHxMxS` format, where:
+* `PT` represents that it is a `Duration`.
+* `xH` represents the number of hours.
+* `xM` represents the number of minutes.
+* `xS` represents the number of seconds.
+. Like a `Period`, when printing a `Duration` only fields with value are displayed. Empty fields are omitted.
+. You can create a `Duration` using `static` methods called `of*`.
+
[source,java,indent=0]
.{java-package}/datetime/duration/Duration_Of.java
@@ -733,7 +730,7 @@ Uma `Duration` é uma quantidade de tempo baseado em hora, como segundos, minuto
include::{section-java-package}/datetime/duration/Duration_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
PT0.000000002S
@@ -746,9 +743,9 @@ PT2.0000002S
PT0.000002S
----
+
-Perceba que `2 dias` é armazenado como 48 horas, pois `Duration` não armazena dias.
+Note that `2 days` is stored as 48 hours because `Duration` does not store days.
-. Também é possível criar uma `Duration` a partir de dois `LocalTime`.
+. You can also create a `Duration` from two `LocalTime`.
+
[source,java,indent=0]
.{java-package}/datetime/duration/Duration_Between.java
@@ -756,7 +753,7 @@ Perceba que `2 dias` é armazenado como 48 horas, pois `Duration` não armazena
include::{section-java-package}/datetime/duration/Duration_Between.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
PT12H
@@ -764,7 +761,7 @@ PT-12H
PT0S
----
-. `Duration` converte automaticamente segundos em minutos e minutos em horas.
+. `Duration` automatically converts seconds to minutes and minutes to hours.
+
[source,java,indent=0]
.{java-package}/datetime/duration/Duration_BiggerValues.java
@@ -772,7 +769,7 @@ PT0S
include::{section-java-package}/datetime/duration/Duration_BiggerValues.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
PT2H
@@ -781,7 +778,7 @@ PT1H59M
PT2H46M40S
----
-. É possível somar uma `Duration` a um `Instant`, `LocalTime` ou `LocalDateTime`.
+. You can add a `Duration` to an `Instant`, `LocalTime` or `LocalDateTime`.
+
[source,java,indent=0]
.{java-package}/datetime/duration/Duration_Compatibility.java
@@ -789,7 +786,7 @@ PT2H46M40S
include::{section-java-package}/datetime/duration/Duration_Compatibility.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Duration: PT2H
@@ -804,7 +801,7 @@ LocalDateTime: 2018-05-27T13:01:01
LocalDateTime + Duration: 2018-05-27T15:01:01
----
-. *Não* é possível somar uma `Duration` a uma `LocalDate`, pois o primeiro representa tempo baseado em hora, enquanto o outro armazena apenas datas.
+. It is *not* possible to add a `Duration` to a `LocalDate`, since the former represents hour time-based, while the other only store dates.
+
[source,java,indent=0]
.{java-package}/datetime/duration/Duration_LocalDate.java
@@ -812,7 +809,7 @@ LocalDateTime + Duration: 2018-05-27T15:01:01
include::{section-java-package}/datetime/duration/Duration_LocalDate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Duration: PT2H
@@ -825,14 +822,14 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
at org.j6toj8.localization.datetime.duration.Duration_LocalDate.main(Duration_LocalDate.java:15)
----
+
-Veja que ocorreu exceção ao tentar somar uma `Duration` a uma `LocalDate`.
+Note that an exception occurred while trying to add a `Duration` to a `LocalDate`.
-.Referências
+.References
****
* Working with Dates and Times
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 234). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 234). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-date-time-intro[Introduction to the Java 8 Date/Time API.]
@@ -840,4 +837,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime/32443004[What's the difference between Instant and LocalDateTime?]
-****
\ No newline at end of file
+****
diff --git a/book/03-localization/sections/04-formats.asc b/book/03-localization/sections/04-formats.asc
index 6add8bf..488f256 100644
--- a/book/03-localization/sections/04-formats.asc
+++ b/book/03-localization/sections/04-formats.asc
@@ -2,28 +2,26 @@
:java-package: src/org/j6toj8/localization
:section-java-package: ../../../{java-package}
-=== Formatação de Números e Datas
+=== Format dates and numbers
-.Objetivo
+.Objective
--------------------------------------------------
Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes, including number and date format patterns.
--
-Formatar datas, números e valores monetários para localização utilizando as classes NumberFormat e DateFormat, incluindo padrões de formato de número e data.
--------------------------------------------------
-Ainda dentro do assunto de Localização e Internacionalização, é comum a necessidade de apresentar datas, números e valores monetários em diferentes formatos.
+Still, within the subject of Localization and Internationalization, it is common the need to present dates, numbers and monetary values in different formats.
-O exame de certificação compreende cinco classes principais de formatação:
+The certification exam covers five main formatting classes:
-* `NumberFormat` -> Formatação geral de números, valores monetários, percentuais e números inteiros com arredondamento, possivelmente baseados em `Locale`.
-* `DecimalFormat` -> Formatação de números quando há necessidade de definições mais específicas ou personalizadas do formato.
-* `DateFormat` -> Formatação de data e hora antes do Java 8 utilizando formatos predefinidos.
-* `SimpleDateFormat` -> Formatação de data e hora antes do Java 8 utilizando formatos mais específicos ou personalizados.
-* `DateTimeFormatter` -> Formatação de data e hora após o Java 8.
+* `NumberFormat` -> General formatting of numbers, monetary values, percentages, and rounded integers, possibly based on `Locale`.
+* `DecimalFormat` -> Number formatting when more specific or custom format definitions are required.
+* `DateFormat` -> Date and time formatting before Java 8 using predefined formats.
+* `SimpleDateFormat` -> Date and time formatting before Java 8 using more specific or custom formats.
+* `DateTimeFormatter` -> Date and time formatting after Java 8.
==== NumberFormat
-. É possível obter uma instância de `NumberFormat` a partir de vários métodos estáticos, dependendo da necessidade.
+. You can get an instance of `NumberFormat` from several static methods, depending on your need.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_Instance.java
@@ -31,9 +29,9 @@ O exame de certificação compreende cinco classes principais de formatação:
include::{section-java-package}/formats/numberformat/NumberFormat_Instance.java[tag=code]
----
+
-Lembre-se que, se não for informado o `Locale`, será utilizado o padrão. O ideal é sempre informar o `Locale`.
+Remember that if you do not enter `Locale`, the default will be used. Ideally, always inform `Locale`.
-. O `NumberFormat` pode ser utilizado para transformar números em Strings.
+. `NumberFormat` can be used to transform numbers into strings.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_NumberToString.java
@@ -41,7 +39,7 @@ Lembre-se que, se não for informado o `Locale`, será utilizado o padrão. O id
include::{section-java-package}/formats/numberformat/NumberFormat_NumberToString.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR: 1.000,05
@@ -49,9 +47,9 @@ en_US: 1,000.05
fr_FR: 1 000,05
----
+
-Perceba que a representação do número muda de acordo com o `Locale`.
+Note that the representation of the number changes according to `Locale`.
-. O `NumberFormat` por ser utilizado para transformar Strings em números.
+. The `NumberFormat` can be used to transform strings into numbers.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_StringToNumber.java
@@ -59,7 +57,7 @@ Perceba que a representação do número muda de acordo com o `Locale`.
include::{section-java-package}/formats/numberformat/NumberFormat_StringToNumber.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR: 1000.05
@@ -67,9 +65,9 @@ en_US: 100005
fr_FR: 1000.05
----
+
-Perceba que dependendo do `Locale` estamos representando um número diferente, e isso muda o resultado do parse.
+Note that depending on `Locale` we are representing a different number, and this changes the parse result.
-. O `NumberFormat` pode ser utilizado para transformar Strings em valores monetários, e vice-versa.
+. `NumberFormat` can be used to transform strings into monetary values, and vice versa.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_Currency.java
@@ -77,7 +75,7 @@ Perceba que dependendo do `Locale` estamos representando um número diferente, e
include::{section-java-package}/formats/numberformat/NumberFormat_Currency.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR: R$ 1.000,05
@@ -88,9 +86,9 @@ Unparseable number: "R$ 1000,05"
Unparseable number: "R$ 1000,05"
----
+
-Perceba que novamente o resultado muda de acordo com o `Locale`. Além disso, não é possível converter a representação da moeda brasileira com um `Locale` `en_US` ou `fr_FR`.
+Note again that the result changes according to `Locale`. Also, it is not possible to convert the representation of the Brazilian currency with a `en_US` or `fr_FR` `Locale`.
-. O `NumberFormat` pode ser utilizado para transformar Strings em percentuais, e vice-versa.
+. `NumberFormat` can be used to transform strings into percentages, and vice versa.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_Percent.java
@@ -98,7 +96,7 @@ Perceba que novamente o resultado muda de acordo com o `Locale`. Além disso, n
include::{section-java-package}/formats/numberformat/NumberFormat_Percent.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR: 90%
@@ -109,9 +107,9 @@ en_US: 0.8
Unparseable number: "80%"
----
+
-Veja que, ao formatar, `100%` é `1`, logo `80%` é `0,8`. Além disso, no `Locale fr_FR` a representação `80%` não é válida.
+Note that when formatting, `100%` is `1`, so `80%` is `0.8`. Also, in `Locale fr_FR`, the `80%` representation is not valid.
-. O `NumberFormat` pode ficar complicado ao lidar com vírgulas.
+. `NumberFormat` can get complicated when dealing with commas.
+
[source,java,indent=0]
.{java-package}/formats/numberformat/NumberFormat_Percent2.java
@@ -119,27 +117,27 @@ Veja que, ao formatar, `100%` é `1`, logo `80%` é `0,8`. Além disso, no `Loca
include::{section-java-package}/formats/numberformat/NumberFormat_Percent2.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
pt_BR: 0.802
en_US: 8.02
----
+
-No `Locale pt_BR` temos o resultado esperado. Porém, no `Locale en_US` o `80,2%` se torna `802%` pois a vírgula não é usada como separador de decimal.
+In `pt_BR` `Locale` we have the expected result. However, in `en_US` `Locale`, `80.2%` becomes `802%` because the comma is not used as a decimal separator.
==== DecimalFormat
-Enquanto `NumberFormat` permite utilizar formatos predefinidos, `DecimalFormat` permite uma personalização maior. Um exemplo de formato para o `DecimalFormat` é `\#\##,\###.\###`.
+While `NumberFormat` allows you to use predefined formats, `DecimalFormat` allows for greater customization. An example format for `DecimalFormat` is `\#\##,\###.\###`.
-* `#` -> preenche a posição com um número, ou omite se não houver nada.
-* `0` -> preenche a posição com um número, ou 0 se não houver nada.
-* `.` -> indica onde é a posição do separador decimal.
-* `,` -> indica onde é a posição do separador de grupos.
+* `#` -> fills the position with a number, or omits if there is nothing.
+* `0` -> fills the position with a number, or 0 if there is nothing.
+* `.` -> indicates where the position of the decimal separator is.
+* `,` -> indicates where the group separator position is.
-//-- ASC: força uma nova lista não associada aos bullets acima
+//-- ASC: force a new list not associated with the bullets above
-. É possível obter uma instância de `DecimalFormat` utilizando o construtor.
+. You can get an instance of `DecimalFormat` using the constructor.
+
[source,java,indent=0]
.{java-package}/formats/decimalformat/DecimalFormat_Instance.java
@@ -147,7 +145,7 @@ Enquanto `NumberFormat` permite utilizar formatos predefinidos, `DecimalFormat`
include::{section-java-package}/formats/decimalformat/DecimalFormat_Instance.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
###,###.###: 12.345,67
@@ -159,9 +157,9 @@ include::{section-java-package}/formats/decimalformat/DecimalFormat_Instance.jav
###: 12346
----
+
-Estou executando o código onde o `Locale` padrão é `pt_BR`, por isso a saída no console apresenta vírgulas para separar grupos e pontos para separar os decimais.
+I'm running code where the default `Locale` is `pt_BR`, so the console output has commas to separate groups and periods to separate decimals.
-. Para utilizar um `Locale` específico é necessário instanciar um `NumberFormat` e fazer um _cast_ para `DecimalFormat`.
+. To use a specific `Locale` it is necessary to instantiate a `NumberFormat` and _cast_ to `DecimalFormat`.
+
[source,java,indent=0]
.{java-package}/formats/decimalformat/DecimalFormat_Locale.java
@@ -169,13 +167,13 @@ Estou executando o código onde o `Locale` padrão é `pt_BR`, por isso a saída
include::{section-java-package}/formats/decimalformat/DecimalFormat_Locale.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
12,345.67
----
-. É possível colocar outros símbolos ou palavras no formato do `DecimalFormat`.
+. You can put other symbols or words in the format of `DecimalFormat`.
+
[source,java,indent=0]
.{java-package}/formats/decimalformat/DecimalFormat_Strings.java
@@ -183,19 +181,19 @@ include::{section-java-package}/formats/decimalformat/DecimalFormat_Locale.java[
include::{section-java-package}/formats/decimalformat/DecimalFormat_Strings.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Número 12.345,67 formatado
+Number 12.345,67 formatted
----
==== DateFormat
-Para formatar Data e Hora antes do Java 8, são utilizadas as classes de `DateFormat` e `SimpleDateFormat`. Essas classes trabalham em geral com a classe `Date` e fazem parte do pacote `java.text`, diferente de `DateTimeFormatter` que é do novo pacote `java.time.format`.
+To format Date and Time before Java 8, the `DateFormat` and `SimpleDateFormat` classes are used. These classes generally work with the `Date` class and are part of the `java.text` package, unlike `DateTimeFormatter` which is from the new `java.time.format` package.
-. Obter instâncias de `DateFormat` é muito parecido com `NumberFormat`.
-. É possível definir o formato das instâncias como `SHORT`, `MEDIUM`, `LONG` ou `FULL`.
-. É possível definir o `Locale` das instâncias.
+. Getting instances of `DateFormat` is a lot like `NumberFormat`.
+. You can set the instance format to `SHORT`, `MEDIUM`, `LONG` or `FULL`.
+. You can define the `Locale` of instances.
+
[source,java,indent=0]
.{java-package}/formats/dateformat/DateFormat_Instance.java
@@ -203,7 +201,7 @@ Para formatar Data e Hora antes do Java 8, são utilizadas as classes de `DateFo
include::{section-java-package}/formats/dateformat/DateFormat_Instance.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
08/09/2001
@@ -213,7 +211,7 @@ include::{section-java-package}/formats/dateformat/DateFormat_Instance.java[tag=
September 8, 2001 10:46:40 PM BRT
----
-. Também é possível transformar `String` em `Date` utilizando o método `parse`.
+. It is also possible to transform `String` to `Date` using the `parse` method.
+
[source,java,indent=0]
.{java-package}/formats/dateformat/DateFormat_Parse.java
@@ -221,7 +219,7 @@ September 8, 2001 10:46:40 PM BRT
include::{section-java-package}/formats/dateformat/DateFormat_Parse.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Sat Sep 08 00:00:00 BRT 2001
@@ -230,30 +228,30 @@ Sat Sep 08 22:46:00 BRT 2001
Unparseable date: "08/09/2001"
----
+
-Perceba que ocorreu uma exceção ao tentar converter uma data utilizando um formatar que espera Data e Hora.
+Note that an exception occurred while trying to convert a date using a format that expects Date and Time.
==== SimpleDateFormat
-A classe `SimpleDateFormat` permite criar formatos mais personalizados para apresentar Data e Hora, como `dd/MM/yyyy HH:mm:ss`. A seguir, as letras mais importantes utilizadas na formatação para o exame:
+The `SimpleDateFormat` class allows you to create more customized formats for displaying Date and Time, such as `dd/MM/yyyy HH:mm:ss`. The following are the most important letters used for exam formatting:
-* `y` -> Ano (2019, 19)
-* `M` -> Mês (8, 08, Ago, Agosto)
-* `d` -> Dia (06)
-* `h` -> Hora em formato AM/PM
-* `H` -> Hora em formato 24H
-* `m` -> Minutos
-* `s` -> Segundos
+* `y` -> Year (2019, 19)
+* `M` -> Month (8, 08, Aug, August)
+* `d` -> Day (06)
+* `h` -> Time in AM / PM format
+* `H` -> Time in 24H format
+* `m` -> Minutes
+* `s` -> Seconds
-Em geral (existem exceções), quanto mais letras forem utilizadas, mais extenso é o formato apresentado. Por exemplo:
+In general (there are exceptions), the more letters are used, the longer the format presented. For example:
* `M` -> 8
* `MM` -> 08
-* `MMM` -> Ago
-* `MMMM` -> Agosto
+* `MMM` -> Aug
+* `MMMM` -> August
-//-- ASC: força uma nova lista não associada aos bullets acima
+//-- ASC: force a new list not associated with the bullets above
-. É possível criar formatos personalizados para formatar um `Date` utilizando o construtor de `SimpleDateFormat`.
+. You can create custom formats to format a `Date` using the `SimpleDateFormat` constructor.
+
[source,java,indent=0]
.{java-package}/formats/simpledateformat/SimpleDateFormat_Instance.java
@@ -261,7 +259,7 @@ Em geral (existem exceções), quanto mais letras forem utilizadas, mais extenso
include::{section-java-package}/formats/simpledateformat/SimpleDateFormat_Instance.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
08 09 01 - 22 46 40
@@ -269,7 +267,7 @@ include::{section-java-package}/formats/simpledateformat/SimpleDateFormat_Instan
22 46 40
----
-. Também é possível criar `Date` a partir de `String` utilizando o método `parse`.
+. You can also create `Date` from `String` using the `parse` method.
+
[source,java,indent=0]
.{java-package}/formats/simpledateformat/SimpleDateFormat_Parse.java
@@ -277,7 +275,7 @@ include::{section-java-package}/formats/simpledateformat/SimpleDateFormat_Instan
include::{section-java-package}/formats/simpledateformat/SimpleDateFormat_Parse.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Sat Sep 08 22:46:40 BRT 2001
@@ -286,13 +284,13 @@ Thu Jan 01 22:46:40 BRT 1970
Unparseable date: "22 46 40"
----
+
-Perceba a exceção ao tentar utilizar o formato incorreto.
+Note the exception when trying to use the wrong format.
==== DateTimeFormatter
-O Java 8 traz a classe `DateTimeFormatter` que possui várias formas de formatar e transformar `Data/Hora` em `String`, e vice-versa.
+Java 8 brings the `DateTimeFormatter` class which has several ways to format and transform `Date/Time` into `String`, and vice versa.
-. É possível obter instâncias predefinidas de `DateTimeFormatter`, que representam formatos `ISO` ou `RFC`.
+. You can get predefined instances of `DateTimeFormatter`, which represent `ISO` or `RFC` formats.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Predefined.java
@@ -300,7 +298,7 @@ O Java 8 traz a classe `DateTimeFormatter` que possui várias formas de formatar
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Predefined.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-08-06
@@ -310,7 +308,7 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Pred
2019-W32-2
----
-. É possível obter instâncias predefinidas de `DateTimeFormatter`, que representam formatos localizados, através da classe `FormatStyle`.
+. You can get predefined instances of `DateTimeFormatter`, which represent localized formats, through the `FormatStyle` class.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_FormatStyle.java
@@ -318,7 +316,7 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Pred
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_FormatStyle.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
06/08/19 11:40
@@ -327,9 +325,9 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Form
11:40
----
+
-O resultado depende de onde o código está sendo executado. Este código foi executado no `Locale` padrão `pt_BR`.
+The result depends on where the code is being executed. This code was executed in the default `pt_BR` `Locale`.
-. É possível alterar o `Locale` utilizado pelo `DateTimeFormatter`.
+. You can change the `Locale` used by `DateTimeFormatter`.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Locale.java
@@ -337,14 +335,14 @@ O resultado depende de onde o código está sendo executado. Este código foi ex
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Locale.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
8/6/19 11:40 AM
Aug 6, 2019 11:40:00 AM
----
-. É possível obter instâncias personalizadas de `DateTimeFormatter`.
+. You can get custom instances of `DateTimeFormatter`.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Custom.java
@@ -352,16 +350,15 @@ Aug 6, 2019 11:40:00 AM
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Custom.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
06 08 19 - 11 40 00
----
+
-Para criar um `DateTimeFormatter` personalizado é necessário conhecer o que cada letra do formato representa. Volte na seção de `SimpleDateFormat` caso não se lembre.
-+
+To create a custom `DateTimeFormatter` you need to know what each letter of the format represents. Return to the `SimpleDateFormat` section if you do not remember.
-. Não é possível formatar uma Data/Hora caso o objeto fornecido não tenha os campos necessários. Um exemplo seria tentar apresentar a Data e fornecer um `LocalTime`.
+. You cannot format a Date/Time if the given object does not have the required fields. An example would be to try to present the Date and provide a `LocalTime`.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Error.java
@@ -369,7 +366,7 @@ Para criar um `DateTimeFormatter` personalizado é necessário conhecer o que ca
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Error.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-08-06
@@ -387,7 +384,7 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
at org.j6toj8.localization.formats.datetimeformatter.DateTimeFormatter_Error.main(DateTimeFormatter_Error.java:18)
----
-. O mesmo erro pode ocorrer ao utilizar um formato personalizado.
+. The same error may occur when using a custom format.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java
@@ -395,7 +392,7 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
11 40 00
@@ -412,9 +409,9 @@ Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException:
at org.j6toj8.localization.formats.datetimeformatter.DateTimeFormatter_ErrorCustom.main(DateTimeFormatter_ErrorCustom.java:20)
----
+
-Nesse caso é lançada exceção porque `LocalDate` não possui hora, minuto ou segundo.
+In this case, an exception is thrown because `LocalDate` has no hour, minute, or second.
-. Também é possível fazer o oposto: converter uma `String` em uma classe de `Data/Hora`. Para isso existem os métodos `parse`.
+. You can also do the opposite: convert a `String` to a `Date/Time` class. For this, there are the `parse` methods.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Parse.java
@@ -422,7 +419,7 @@ Nesse caso é lançada exceção porque `LocalDate` não possui hora, minuto ou
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Parse.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-08-06T11:40
@@ -430,7 +427,7 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Pars
2019-08-06T11:40
----
-. Todos os métodos utilizados para `format` e `parse` também podem ser invocados diretamente na instância do `DateTimeFormatter`.
+. All methods used to `format` and `parse` can also be invoked directly in the `DateTimeFormatter` instance.
+
[source,java,indent=0]
.{java-package}/formats/datetimeformatter/DateTimeFormatter_Inverted.java
@@ -438,7 +435,7 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Pars
include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Inverted.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-08-06T11:40
@@ -447,19 +444,19 @@ include::{section-java-package}/formats/datetimeformatter/DateTimeFormatter_Inve
2019-08-06T11:40
----
+
-Porém, veja que ao utilizar o método `parse` diretamente no `DateTimeFormatter`, é necessário converter o resultado para um `LocalDateTime`.
+However, note that when using the `parse` method directly in `DateTimeFormatter`, it is necessary to convert the result to a `LocalDateTime`.
-.Referências
+.References
****
* Adding Internationalizationand Localization
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 255). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 255). Wiley. Kindle Edition.
* Formatting and Parsing
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 603). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 603). Wiley. Kindle Edition.
* https://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string[Change date format in a Java string.] BalusC.
@@ -477,4 +474,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/java/data/numberformat.html[Formatting Numeric Print Output] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/03-localization/sections/05-time-zones.asc b/book/03-localization/sections/05-time-zones.asc
index 0fa1bbe..60102f1 100644
--- a/book/03-localization/sections/05-time-zones.asc
+++ b/book/03-localization/sections/05-time-zones.asc
@@ -1,22 +1,20 @@
:java-package: src/org/j6toj8/localization
:section-java-package: ../../../{java-package}
-=== Fusos Horários
+=== Time zones
-.Objetivo
+.Objective
--------------------------------------------------
Work with dates and times across time zones and manage changes resulting from daylight savings.
--
-Trabalhe com datas e horas entre fusos horários e gerencie alterações resultantes de horários de verão.
--------------------------------------------------
-O exame de certificação espera que você consiga lidar com diferentes fusos horários, além de conseguir entender o que ocorre ao realizar operações com datas e horas que passam por um horário de verão.
+The certification exam expects you to be able to cope with different time zones, as well as understanding what happens when you perform operations with dates and times that go through daylight saving time.
-Nessa seção será apresenta a classe `ZonedDateTime`, que armazena Data, Hora e um fuso horário. Ou seja, é muito parecida com a classe `LocalDateTime`, porém possui um fuso horário.
+This section will introduce the `ZonedDateTime` class, which stores Date, Time and a time zone. That is, it is very similar to the `LocalDateTime` class, but has a time zone.
-A representação de um `ZonedDateTime` é `2007-12-03T10:15:30+01:00 Europe/Paris`.
+The representation of a `ZonedDateTime` is `2007-12-03T10:15:30+01:00 Europe/Paris`.
-. É possível criar um `ZonedDateTime` através do método `static` chamado `now`.
+. You can create a `ZonedDateTime` via the `static` method called `now`.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Now.java
@@ -24,15 +22,15 @@ A representação de um `ZonedDateTime` é `2007-12-03T10:15:30+01:00 Europe/Par
include::{section-java-package}/timezones/ZonedDateTime_Now.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-06-09T18:10:08.863-03:00[America/Sao_Paulo]
----
+
-A saída no console irá apresentar a data e hora atual, e o fuso horário de onde o código está sendo executado.
+The console output will display the current date and time, and the time zone from which the code is being executed.
-. Também é possível criar um `ZonedDateTime` através do método `static` chamado `of`.
+. It is also possible to create a `ZonedDateTime` through the `static` method called `of`.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Of.java
@@ -40,7 +38,7 @@ A saída no console irá apresentar a data e hora atual, e o fuso horário de on
include::{section-java-package}/timezones/ZonedDateTime_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-06-09T13:20:03.000001-03:00[America/Sao_Paulo]
@@ -48,9 +46,9 @@ include::{section-java-package}/timezones/ZonedDateTime_Of.java[tag=code]
2019-06-09T13:20:03.000001-03:00[America/Sao_Paulo]
----
+
-Perceba que é possível criar um `ZonedDateTime` diretamente, ou através de um `LocalDateTime`, ou com uma junção de um `LocalDate` e um `LocalTime`. Note que em todos os casos é necessário informar o fuso horário.
+Note that it is possible to create a `ZonedDateTime` directly, either through a `LocalDateTime`, or with a join of a `LocalDate` and a `LocalTime`. Note that in all cases it is necessary to enter the time zone.
-. Assim como todas a novas classes de data e hora, não é possível criar uma instância de `ZonedDateTime` utilizando o construtor.
+. As with all new date and time classes, you cannot create an instance of `ZonedDateTime` using the constructor.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Constructor.java
@@ -58,7 +56,7 @@ Perceba que é possível criar um `ZonedDateTime` diretamente, ou através de um
include::{section-java-package}/timezones/ZonedDateTime_Constructor.java[tag=code]
----
-. Será lançada a exceção `DateTimeException` ao tentar criar uma data inválida.
+. The `DateTimeException` exception will be thrown when trying to create an invalid date.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Invalid.java
@@ -66,7 +64,7 @@ include::{section-java-package}/timezones/ZonedDateTime_Constructor.java[tag=cod
include::{section-java-package}/timezones/ZonedDateTime_Invalid.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
@@ -77,7 +75,7 @@ Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
at org.j6toj8.localization.timezones.ZonedDateTime_Invalid.main(ZonedDateTime_Invalid.java:10)
----
-. Existem vários métodos para somar e subtrair de `ZonedDateTime`
+. There are several methods for adding and subtracting from `ZonedDateTime`
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Manipulate.java
@@ -85,36 +83,35 @@ Exception in thread "main" java.time.DateTimeException: Invalid date 'APRIL 31'
include::{section-java-package}/timezones/ZonedDateTime_Manipulate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 horas: 2019-05-20T11:20:12.000001-03:00[America/Sao_Paulo]
-+2 minutos: 2019-05-20T09:22:12.000001-03:00[America/Sao_Paulo]
-+2 segundos: 2019-05-20T09:20:14.000001-03:00[America/Sao_Paulo]
-+2 nanosegundos: 2019-05-20T09:20:12.000001002-03:00[America/Sao_Paulo]
-+2 microssegundos: 2019-05-20T09:20:12.000003-03:00[America/Sao_Paulo]
-+2 milissegundos: 2019-05-20T09:20:12.002001-03:00[America/Sao_Paulo]
--2 horas: 2019-05-20T07:20:12.000001-03:00[America/Sao_Paulo]
--2 minutos: 2019-05-20T09:18:12.000001-03:00[America/Sao_Paulo]
--2 segundos: 2019-05-20T09:20:10.000001-03:00[America/Sao_Paulo]
--2 nanosegundos: 2019-05-20T09:20:12.000000998-03:00[America/Sao_Paulo]
--2 microssegundos: 2019-05-20T09:20:11.999999-03:00[America/Sao_Paulo]
--2 milissegundos: 2019-05-20T09:20:11.998001-03:00[America/Sao_Paulo]
-+2 dias: 2019-05-22T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 semanas: 2019-06-03T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 meses: 2019-07-20T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 anos: 2021-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 anos: 2021-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
-+2 décadas: 2039-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
--2 dias: 2019-05-18T09:20:12.000001-03:00[America/Sao_Paulo]
--2 semanas: 2019-05-06T09:20:12.000001-03:00[America/Sao_Paulo]
--2 meses: 2019-03-20T09:20:12.000001-03:00[America/Sao_Paulo]
--2 anos: 2017-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
--2 décadas: 1999-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
-----
-
-. `ZonedDateTime` é imutável, então é necessário armazenar o retorno de uma alteração em uma variável.
++2 hours: 2019-05-20T11:20:12.000001-03:00[America/Sao_Paulo]
++2 minutes: 2019-05-20T09:22:12.000001-03:00[America/Sao_Paulo]
++2 seconds: 2019-05-20T09:20:14.000001-03:00[America/Sao_Paulo]
++2 nanoseconds: 2019-05-20T09:20:12.000001002-03:00[America/Sao_Paulo]
++2 microseconds: 2019-05-20T09:20:12.000003-03:00[America/Sao_Paulo]
++2 milliseconds: 2019-05-20T09:20:12.002001-03:00[America/Sao_Paulo]
+-2 hours: 2019-05-20T07:20:12.000001-03:00[America/Sao_Paulo]
+-2 minutes: 2019-05-20T09:18:12.000001-03:00[America/Sao_Paulo]
+-2 seconds: 2019-05-20T09:20:10.000001-03:00[America/Sao_Paulo]
+-2 nanoseconds: 2019-05-20T09:20:12.000000998-03:00[America/Sao_Paulo]
+-2 microseconds: 2019-05-20T09:20:11.999999-03:00[America/Sao_Paulo]
+-2 milliseconds: 2019-05-20T09:20:11.998001-03:00[America/Sao_Paulo]
++2 days: 2019-05-22T09:20:12.000001-03:00[America/Sao_Paulo]
++2 weeks: 2019-06-03T09:20:12.000001-03:00[America/Sao_Paulo]
++2 months: 2019-07-20T09:20:12.000001-03:00[America/Sao_Paulo]
++2 years: 2021-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
++2 decades: 2039-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
+-2 days: 2019-05-18T09:20:12.000001-03:00[America/Sao_Paulo]
+-2 weeks: 2019-05-06T09:20:12.000001-03:00[America/Sao_Paulo]
+-2 months: 2019-03-20T09:20:12.000001-03:00[America/Sao_Paulo]
+-2 years: 2017-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
+-2 decades: 1999-05-20T09:20:12.000001-03:00[America/Sao_Paulo]
+----
+
+. `ZonedDateTime` is immutable, so you must store the return of a change in a variable.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Immutability.java
@@ -122,7 +119,7 @@ include::{section-java-package}/timezones/ZonedDateTime_Manipulate.java[tag=code
include::{section-java-package}/timezones/ZonedDateTime_Immutability.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20:03.000000300-03:00[America/Sao_Paulo]
@@ -130,7 +127,7 @@ include::{section-java-package}/timezones/ZonedDateTime_Immutability.java[tag=co
2019-05-20T10:20:03.000000300-03:00[America/Sao_Paulo]
----
-. É comum utilizar o encadeamento de chamadas com esses métodos.
+. It is common to use call chaining with these methods.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Chaining.java
@@ -138,14 +135,14 @@ include::{section-java-package}/timezones/ZonedDateTime_Immutability.java[tag=co
include::{section-java-package}/timezones/ZonedDateTime_Chaining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-05-20T09:20:04.000000300-03:00[America/Sao_Paulo]
2020-05-21T10:20:04.000000300-03:00[America/Sao_Paulo]
----
-. Ao manipular um `ZonedDateTime`, será levado em conta o horário de verão daquele fuso horário.
+. When handling a `ZonedDateTime`, the daylight saving time of that time zone will be taken into account.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_DaylightSavings.java
@@ -153,16 +150,16 @@ include::{section-java-package}/timezones/ZonedDateTime_Chaining.java[tag=code]
include::{section-java-package}/timezones/ZonedDateTime_DaylightSavings.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2018-11-03T23:30-03:00[America/Sao_Paulo]
-+2 horas: 2018-11-04T02:30-02:00[America/Sao_Paulo]
++2 hours: 2018-11-04T02:30-02:00[America/Sao_Paulo]
----
+
-Neste exemplo o fuso horário que era `-03:00` virou `-02:00`, pois esse foi o dia em que teve início o horário de verão no Brasil. Outro detalhe é que por conta do horário de verão, ao somar 2 horas às `23:30` resultou em `02:30` do dia seguinte. Se não houvesse horário de verão, o resultado seria `01:30`.
+In this example, the time zone that was `-03:00` became `-02:00`, because that was beginning of the day daylight savings time in Brazil. Another detail is that because of daylight saving time, adding 2 hours at 23:30 resulted in 02:30 the next day. If there was no daylight saving time, the result would be `01: 30`.
-. É possível recuperar todos os fusos horários disponíveis através da classe `ZoneId`.
+. You can retrieve all available time zones through the `ZoneId` class.
+
[source,java,indent=0]
.{java-package}/timezones/ZonedDateTime_Zones.java
@@ -170,7 +167,7 @@ Neste exemplo o fuso horário que era `-03:00` virou `-02:00`, pois esse foi o d
include::{section-java-package}/timezones/ZonedDateTime_Zones.java[tag=code]
----
+
-.Saída no console (parcial)
+.console output (parcial)
[source,console]
----
Asia/Aden
@@ -193,16 +190,16 @@ America/Guatemala
...
----
+
-A lista do console irá apresentar todos os `ZoneId` disponíveis. O exemplo acima contempla apeanas parte dos `ZoneId`.
+The console list will display all available `ZoneId`. The above example only contemplates part of `ZoneId`.
+
-Além disso, existem muitos `ZoneId` duplicados, pois representam o mesmo fuso horário, como por exemplo `America/Sao_Paulo` e `Brazil/East`.
+Also, there are many duplicate `ZoneId` as they represent the same time zone as for example `America/Sao_Paulo` and `Brazil/East`.
-.Referências
+.References
****
* Working with Dates and Times
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 234). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 234). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-date-time-intro[Introduction to the Java 8 Date/Time API.]
diff --git a/book/04-lambda/sections/01-functional-interfaces.asc b/book/04-lambda/sections/01-functional-interfaces.asc
index eeb34cc..d9bd830 100644
--- a/book/04-lambda/sections/01-functional-interfaces.asc
+++ b/book/04-lambda/sections/01-functional-interfaces.asc
@@ -1,19 +1,17 @@
:java-package: src/org/j6toj8/lambda
:section-java-package: ../../../{java-package}
-=== Interfaces Funcionais (Functional Interfaces)
+=== Functional Interfaces
-.Objetivo
+.Objective
--------------------------------------------------
Define and write functional interfaces and describe the interfaces of the java.util.function package.
--
-Definir e escrever interfaces funcionais e descrever as interfaces do pacote java.util.function.
--------------------------------------------------
-Interfaces funcionais são um novo tipo de Interface do Java. Nesta seção serão apresentados os conceitos e na seção de <> será possível ver como utilizá-las.
+Functional interfaces are a new type of Java Interface. In this section the concepts will be presented and in the <> section you will see how to use them.
-. Interfaces Funcionais são aquelas que possuem apenas um método abstrato, chamado de "método funcional".
-. É recomendada a utilização da anotação `@FunctionalInterface`, mas não obrigatório.
+. Functional Interfaces are those that have only one abstract method, called the "functional method".
+. The use of the `@FunctionalInterface` annotation is recommended, but not required.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Basic.java
@@ -21,9 +19,9 @@ Interfaces funcionais são um novo tipo de Interface do Java. Nesta seção ser
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Basic.java[tag=code]
----
+
-A anotação `@FunctionalInterface` garante, em tempo de compilação, que esta interface é funcional. Também indica para outros desenvolvedores que ela foi criada com o intuito de ser utilizada em expressões lambda, e por isso não se deve criar outros métodos abstratos dentro dela.
+The `@FunctionalInterface` annotation ensures at compile time that this interface is functional. It also indicates to other developers that it was created for use in lambda expressions, so you should not create other abstract methods within it.
-. Métodos adicionais que sejam `default` ou `static` não fazem com que a interface deixe de ser funcional.
+. Additional methods that are `default` or `static` don't make the interface to be functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java
@@ -31,13 +29,13 @@ A anotação `@FunctionalInterface` garante, em tempo de compilação, que esta
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java[tag=code]
----
+
-Lembre-se que os métodos `static` em interfaces podem ser chamados diretamente, como `Executavel.execute(...)`. Dessa forma, não há interferência no fato da interface ser funcional.
+Remember that `static` methods on interfaces can be called directly, such as `Executable.execute (...)`. Thus, there is no interference in the fact that the interface is functional.
+
-Por outro lado, os métodos `default` só podem ser chamados caso você possua uma instância da interface, porém eles já possuem uma implementação padrão.
+On the other hand, `default` methods can only be called if you have an instance of the interface, but they already have a default implementation.
+
-Em caso de dúvidas sobre `static` ou `default` em interfaces, volte na seção de "Métodos _static_ e _default_ em Interfaces".
+If you have questions about `static` or `default` in interfaces, go back to the _"Static and default methods of an interface"_ section.
-. Sobrescrever na interface um método público de `java.lang.Object` também não faz com que ela deixe de ser funcional.
+. Overriding a public method of `java.lang.Object` in the interface doesn't turn it to a no functional interface.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_OverrideObject.java
@@ -45,7 +43,7 @@ Em caso de dúvidas sobre `static` ou `default` em interfaces, volte na seção
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_OverrideObject.java[tag=code]
----
-. Uma interface que estende outra sem acrescentar métodos abstratos também pode ser funcional.
+. An interface that extends another without adding abstract methods can also be functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Extends.java
@@ -53,7 +51,7 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Overri
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Extends.java[tag=code]
----
-. Se uma interface estende outra que é funcional, porém acrescenta novos métodos abstratos, ela não é funcional.
+. If one interface extends another that is functional but adds new abstract methods, it is not functional.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java
@@ -61,7 +59,7 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Extend
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java[tag=code]
----
-. Utilizar a anotação `@FunctionalInterface` em interfaces que possuem mais de um método abstrato causa um erro de compilação.
+. Using the `@FunctionalInterface` annotation on interfaces that have more than one abstract method causes a compilation error.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java
@@ -69,7 +67,7 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Extend
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java[tag=code]
----
-. Utilizar a anotaçao `@FunctionalInterface` em qualquer tipo que não seja uma interface causa um erro de compilação.
+. Using the `@FunctionalInterface` annotation on any type other than an interface causes a compilation error.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java
@@ -77,7 +75,7 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Interf
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java[tag=code]
----
-. Os métodos funcionais podem ter qualquer tipo de retorno.
+. Functional methods can have any return.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_ReturnType.java
@@ -85,7 +83,7 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ClassC
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_ReturnType.java[tag=code]
----
-. Interfaces funcionais são feitas com o intuito de serem utilizadas em expressões lambda, mas o código também irá compilar normalmente caso uma classe a implemente.
+. Functional interfaces are meant to be used in lambda expressions, but the code will also compile normally if a class implements it.
+
[source,java,indent=0]
.{java-package}/functionalinterfaces/FunctionalInterfaces_Implement.java
@@ -93,44 +91,44 @@ include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Return
include::{section-java-package}/functionalinterfaces/FunctionalInterfaces_Implement.java[tag=code]
----
+
-Esse é apenas um exemplo para você saber que essa implementação não gera erro de compilação, mas *não* utilize interfaces funcionais dessa forma. Na seção de Expressões Lambda você verá como as interfaces funcionais devem ser utilizadas na prática.
+This is just an example for you to know that this implementation does not generate compilation errors, but *does not* use functional interfaces in this way. In the Lambda Expressions section, you will see how functional interfaces should be used in practice.
-==== Interfaces Funcionais do pacote `java.util.function`
+==== Functional Interfaces from `java.util.function` package
-As interfaces descritas aqui estão disponíveis no pacote `java.util.function`. Nesta seção serão apresentadas apenas suas definições, pois há posteriormente uma seção específica para tratar dos exemplos de cada uma.
+The interfaces described here are available in the `java.util.function` package. This section will present only its definitions, as there is later a specific section to deal with the examples of each.
-Existem outras interfaces nesse pacote além das listadas aqui, porém são apenas específicas para lidar com tipos primitivos, seguindo as mesmas definições.
+There are other interfaces in this package besides those listed here, but they are only specific to dealing with primitive types, following the same definitions.
-* `Supplier`: Representa um fornecedor de resultados.
+* `Supplier`: Represents a results provider.
+
-Um `Supplier` literalmente apenas fornece dados ou resultados para alguém. Um gerador de números sequenciais, por exemplo, pode ser um `Supplier`.
+A `Supplier` literally only provides data or results to someone. A sequential number generator, for example, may be a `Supplier`.
-* `Consumer`: Representa uma operação que aceita uma única entrada e não possui retorno.
-* `BiConsumer`: Representa uma operação que aceita duas entradas e não possui retorno.
+* `Consumer`: Represents an operation that accepts a single entry and has no return.
+* `BiConsumer`: Represents an operation that accepts two inputs and has no return.
+
-Os `Consumer` são praticamente o inverso dos `Supplier`, pois eles apenas recebem dados ou informações e os tratam de alguma forma.
+`Consumers` are pretty much the opposite of `Supplier`, as they only receive data or information and treat them in some way.
-* `Function`: Representa uma função que aceita um argumento e produz um retorno.
-* `BiFunction`: Representa uma função que aceita dois argumentos e produz um retorno.
+* `Function`: Represents a function that accepts an argument and produces a return.
+* `BiFunction`: Represents a function that takes two arguments and produces a return.
+
-As `Function` são mais parecidas com as funções que já conhecemos. Elas recebem dados e produzem um retorno.
+The `Function` are more similar to the functions we already know. They receive data and produce a return.
-* `Predicate`: Representa uma proposição (função de valor booleano) de um argumento.
-* `BiPredicate`: Representa uma proposição (função de valor booleano) de dois argumentos.
+* `Predicate`: Represents a proposition (Boolean value function) of an argument.
+* `BiPredicate`: Represents a proposition (Boolean value function) of two arguments.
+
-Os `Predicate` são parecidos com as `Function`, porém sempre retornam um resultado booleano, por isso são utilizados para "testes" de verdadeiro ou falso.
+`Predicate` is similar to `Function`, but always returns a Boolean result, so it is used for true or false "tests".
-* `UnaryOperator`: Representa uma operação em um único operador que produz um resultado do mesmo tipo dele.
-* `BinaryOperator`: Representa uma operação em dois operadores que produz um resultado do mesmo tipo deles.
+* `UnaryOperator`: Represents an operation on a single operator that produces a result of the same type as it.
+* `BinaryOperator`: Represents an operation on two operators that produces a result of the same type as them.
+
-Os `Operator` são especializações de `Function`, pois apesar de também sempre recebem e produzirem resultados, as entradas e saídas são sempre do mesmo tipo.
+The `Operator` are `Function` specializations, because although they also always receive and produce results, the inputs and outputs are always the same type.
-.Referências
+.References
****
* Introducing Functional Programming
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 52). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 52). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-functional-interfaces[Functional Interfaces in Java 8.]
@@ -140,4 +138,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/04-lambda/sections/02-lambda-expression.asc b/book/04-lambda/sections/02-lambda-expression.asc
index 973019a..e0d24b2 100644
--- a/book/04-lambda/sections/02-lambda-expression.asc
+++ b/book/04-lambda/sections/02-lambda-expression.asc
@@ -2,31 +2,29 @@
:section-java-package: ../../../{java-package}
[[lambda-expression]]
-=== Expressões Lambda (Lambda Expression)
+=== Lambda Expression
-.Objetivo
+.Objective
--------------------------------------------------
Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing.
--
-Descrever uma expressão lambda; refatorar código que usa classes anônimas internas para usar expressões lambda; descrever a inferência de tipos e tipos esperados.
--------------------------------------------------
-Expressões Lambda são parecidas com classes anônimas, porém só possuem a implementação dos métodos. Por isso, são como "métodos anônimos", que podem ser passados via variáveis.
+Lambda expressions are similar to anonymous classes, but only have the implementation of the methods. Therefore, they are like "anonymous methods" that can be passed via variables.
-É essencial o entendimento de funções lambda, e das variações em sua sintaxe, para compreender as próximas seções de Interfaces Funcionais Pré-Construídas e de Referências a métodos.
+Understanding lambda functions, and variations in their syntax, is essential to understanding the next sections of Built-in Interfaces and Method References.
-A expressão lambda possui 3 partes:
+The lambda expression has 3 parts:
-. Uma lista de parâmetros, separados por vírgula
-* Algumas vezes possui parênteses
-* Algumas vezes possui o tipo das variáveis
-. O "arrow token", que sempre é escrito como `\->`
-. Um corpo, que pode ou não estar entre chaves
-* Pode possuir mais de uma linha
-* Algumas vezes possui um `return`
-* Algumas vezes possui ponto e vírgula
+. A comma-separated list of parameters
+* Sometimes has parentheses
+* Sometimes has variable type
+. The "arrow token", which is always written as `\->`
+. A body, which may or may not be enclosed in braces
+* Can have more than one line
+* Sometimes has a `return`
+* Sometimes has semicolon
-Exemplos de expressões lambda:
+Examples of lambda expressions:
* `i -> System.out.println(i)`
* `(Integer i) -> System.out.println(i)`
@@ -34,11 +32,11 @@ Exemplos de expressões lambda:
* `(Integer i) -> { return i + 1; }`
* `(i, j, k) -> { return i + j + k; }`
* `(i, j, k) -> System.out.println(i + j + k)`
-* `() -> System.out.println("nada")`
+* `() -> System.out.println("nothing")`
//-
-. Expressões lambda podem ser entendidas como uma forma diferente de declarar classes anônimas.
+. Lambda expressions can be understood as a different way of declaring anonymous classes.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_AnonymousClass.java
@@ -46,9 +44,9 @@ Exemplos de expressões lambda:
include::{section-java-package}/lambdaexpression/LambdaExpression_AnonymousClass.java[tag=code]
----
+
-Veja que no exemplo acima é instanciada uma `Thread` com uma instância anônima de `Runnable`. Na segunda parte, é feito a mesma coisa de forma muito mais simples utilizando uma expressão lambda.
+Note that in the example above a `Thread` is instantiated with an anonymous instance of `Runnable`. In the second part, the same thing is done much simpler using a lambda expression.
-. Expressões lambda são sempre utilizadas para criar instâncias de interfaces funcionais, ou seja, interfaces que possuem apenas um único método abstrato.
+. Lambda expressions are always used to create instances of functional interfaces, i.e., interfaces that have only a single abstract method.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_FunctionalInterface.java
@@ -56,18 +54,18 @@ Veja que no exemplo acima é instanciada uma `Thread` com uma instância anônim
include::{section-java-package}/lambdaexpression/LambdaExpression_FunctionalInterface.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-executei com classe anônima
-executei com expressão lambda
+performed with anonymous class
+performed with lambda expression
----
+
-Veja que no exemplo acima o mesmo método `executeEApresenteMensagem` é invocado duas vezes. Na primeira vez é passada uma nova classe anônima. Na segunda vez é passado uma expressão lambda.
+Note that in the example above the same `executeAndPresentMessage` method is invoked twice. The first time a new anonymous class is passed. The second time a lambda expression is passed.
+
-Veja também que seria impossível criar uma expressão lambda caso a interface não fosse funcional, ou seja, tivesse mais de um método abstrato. O compilador não saberia identificar que o método `execute`, da interface `Executavel`, está sendo implementado dentro da expressão lambda.
+Also see that it would be impossible to create a lambda expression if the interface was not functional, i.e., it had more than one abstract method. The compiler would not be able to identify that the `execute` method of the` Executable` interface is being implemented within the lambda expression.
-. Existem muitos métodos já disponíveis no Java 8 que se beneficiam da sintaxe de expressões lambda, como o `forEach` de listas.
+. There are many methods already available in Java 8 that benefit from lambda expression syntax, such as `forEach` lists.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_ForEach.java
@@ -75,7 +73,7 @@ Veja também que seria impossível criar uma expressão lambda caso a interface
include::{section-java-package}/lambdaexpression/LambdaExpression_ForEach.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
1
@@ -85,11 +83,11 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_ForEach.java[t
5
----
+
-Veja que o novo método `forEach` executa a expressão lambda passada como parâmetro para cada item da lista, imprimindo todos no console. A expressão lambda recebe como parâmetro um número, que é o número da lista.
+Note that the new `forEach` method executes the lambda expression passed as a parameter to each list item, printing them all to the console. The lambda expression takes as a parameter a number, which is the list number.
+
-Neste caso, a interface funcional que está sendo implementada pela expressão lambda é chamada `Consumer`. Ela será explicada em detalhes em uma seção posterior, juntamente com outras interfaces funcionais padrões do Java 8. Nesta seção é importante apenas entender o que são as expressões lambda e como é sua sintaxe.
+In this case, the functional interface being implemented by the lambda expression is called `Consumer`. It will be explained in detail in a later section, along with other standard Java 8 functional interfaces. In this section, it is essential to understand what lambda expressions are and what their syntax is like.
-. Declarações de expressões lambda podem ser completas ou simplificadas.
+. Declarations of lambda expressions can be complete or simplified.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_SimpleComplete.java
@@ -97,10 +95,10 @@ Neste caso, a interface funcional que está sendo implementada pela expressão l
include::{section-java-package}/lambdaexpression/LambdaExpression_SimpleComplete.java[tag=code]
----
+
-As duas funções lambda acima são idênticas, porém uma é mais explícita do que a outra.
+The two lambda functions above are identical, but one is more explicit than the other.
-. Os parênteses só podem ser omitidos caso não haja a declaração do *tipo*, e haja apenas *um único* argumento.
-. Expressões lambda que NÃO possuem argumentos também precisam dos parênteses.
+. Parentheses can only be omitted if there is no *type* declaration, and there is only *a single* argument.
+. Lambda expressions that do NOT have arguments also need parentheses.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_Parenthesis.java
@@ -108,7 +106,7 @@ As duas funções lambda acima são idênticas, porém uma é mais explícita do
include::{section-java-package}/lambdaexpression/LambdaExpression_Parenthesis.java[tag=code]
----
-. É obrigatória a utilização de chaves, ponto e vírgula e `return` (caso a função retorne algum valor) em expressões lambda com mais de uma linha.
+. The use of curly brackets, semicolons and `return` (if the function returns any value) is required in lambda expressions with more than one line.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_Block.java
@@ -116,7 +114,7 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_Parenthesis.ja
include::{section-java-package}/lambdaexpression/LambdaExpression_Block.java[tag=code]
----
-. Ao tornar explícito o tipo de um dos argumentos, é obrigatório informar de todos.
+. When making the type of one of the arguments explicit, it is mandatory to inform all of them.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_VarType.java
@@ -124,7 +122,7 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_Block.java[tag
include::{section-java-package}/lambdaexpression/LambdaExpression_VarType.java[tag=code]
----
-. Não é permitido declarar variáveis com o mesmo nome dentro da expressão lambda.
+. It is not allowed to declare variables with the same name within the lambda expression.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_Shadowing.java
@@ -132,7 +130,7 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_VarType.java[t
include::{section-java-package}/lambdaexpression/LambdaExpression_Shadowing.java[tag=code]
----
-. É permitido acessar variáveis externas dentro da expressão lambda, mas somente variáveis finais ou variáveis que não são alteradas.
+. It is allowed to access external variables within the lambda expression, but only final variables or variables that do not change.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_AccessExternalVar.java
@@ -140,9 +138,9 @@ include::{section-java-package}/lambdaexpression/LambdaExpression_Shadowing.java
include::{section-java-package}/lambdaexpression/LambdaExpression_AccessExternalVar.java[tag=code]
----
+
-Perceba que o compilador identifica que a variável `x3` é alterada no final do método, e por isso, não permite que ela seja utilizada na expressão lambda.
+Note that the compiler identifies that the `x3` variable is changed at the end of the method, and therefore does not allow it to be used in the lambda expression.
-. Em situações de ambiguidade, o compilador tenta descobrir o tipo da expressão lambda utilizando o contexto.
+. In ambiguous situations, the compiler tries to find out the type of lambda expression using the context.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_TypeInference.java
@@ -150,13 +148,13 @@ Perceba que o compilador identifica que a variável `x3` é alterada no final do
include::{section-java-package}/lambdaexpression/LambdaExpression_TypeInference.java[tag=code]
----
+
-No exemplo anterior, apenas o método `run` da interface funcional `Application` retorna uma `String`, enquanto o método `execute` da interface funcional `Executavel` não retorna nada (`void`). Isso é diferença suficiente para o compilador saber qual método chamar cada vez que `rode` é invocado.
-+
-Na primeira chamada ao método `rode`, como a expressão lambda passada retorna uma `String`, o compilador entende que essa expressão lambda é uma implementação da interface `Application`, pois o método `run` também retorna uma `String`.
+In the previous example, only the `run` method of the `Application` functional interface returns a `String`, while the `execute` method of the `Executable` functional interface returns nothing (`void`). This is enough difference for the compiler to know which method to call each time `doThis` is invoked.
+
-Na segunda chamada ao método `rode`, como a expressão lambda não retorna nada (apenas imprime a `String` `"executando"`), o compilador entende que essa expressão lambda é uma implementação da interface `Executavel`, pois o método `execute` também não retorna nada.
+On the first call to the `doThis` method, since the passed lambda expression returns a `String`, the compiler understands that this lambda expression is an implementation of the `Application` interface, as the `run` method also returns a `String`.
++
+On the second call to the `doThis` method, since the lambda expression returns nothing (just prints the `String` `"executing"`), the compiler understands that this lambda expression is an implementation of the `Executable` interface, because the `execute` also returns nothing.
-. Se não for possível descobrir o tipo da expressão lambda, ocorre erro de compilação.
+. If the type of the lambda expression cannot be found, a compilation error occurs.
+
[source,java,indent=0]
.{java-package}/lambdaexpression/LambdaExpression_Ambiguity.java
@@ -164,14 +162,14 @@ Na segunda chamada ao método `rode`, como a expressão lambda não retorna nada
include::{section-java-package}/lambdaexpression/LambdaExpression_Ambiguity.java[tag=code]
----
+
-No exemplo anterior, como as duas interfaces funcionais possuem métodos com retorno `void`, o compilador não sabe qual das duas está sendo instanciada na expressão lambda, e ocorre erro de compilação. A expressão lambda, nesse exemplo, poderia ser tanto do tipo `Piloto` quanto `Corredor`, e não há como o compilador descobrir qual o desenvolvedor de fato quis utilizar.
+In the previous example, because both functional interfaces have a `void` method, the compiler does not know which one is being instantiated in the lambda expression, and a compilation error occurs. The lambda expression in this example could be either `Pilot` or `Runner`, and there is no way for the compiler to find out which developer actually wanted to use it.
-.Referências
+.References
****
* Implementing Functional Interfaces with Lambdas
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 55). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 55). Wiley. Kindle Edition.
* Using Variables in Lambdas
+
@@ -181,4 +179,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/04-lambda/sections/03-built-in-interfaces.asc b/book/04-lambda/sections/03-built-in-interfaces.asc
index c0a9b11..f624913 100644
--- a/book/04-lambda/sections/03-built-in-interfaces.asc
+++ b/book/04-lambda/sections/03-built-in-interfaces.asc
@@ -1,24 +1,22 @@
:java-package: src/org/j6toj8/lambda
:section-java-package: ../../../{java-package}
-=== Interfaces Funcionais Pré-Construídas (Built-in Interfaces)
+=== Built-in Interfaces
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses the built-in interfaces included in the java.util.function package, such as Function, Consumer, Supplier, UnaryOperator, Predicate, and Optional APIs, including the primitive and binary variations of the interfaces
--
-Desenvolver código que usa as interfaces embutidas no pacote java.util.function, como Function, Consumer, Supplier, UnaryOperator, Predicate e a API de Optional, incluindo as variações de tipos primitivos e binários das interfaces
--------------------------------------------------
-==== Interfaces Funcionais
+==== Functional Interfaces
-O Java 8 possui algumas Interfaces Funcionais já criadas. Elas provavelmente serão suficientes para a maioria dos cenários onde é usual utilizar expressões lambda, de tal forma que não deve ser muito comum você precisar criar uma nova.
+Java 8 has some Functional Interfaces already created. They will probably be enough for most scenarios where it is usual to use lambda expressions, so it should not be routine for you to create a new one.
-É fundamental entender esses exemplos para dominar a utilização de expressões lambda, e para entender a próxima seção sobre referências a métodos.
+It is critical to understand these examples to master the use of lambda expressions and to understand the next section on method references.
===== Supplier
-. `Supplier` é uma interface funcional que não recebe nenhum parâmetro de entrada, mas retorna um valor. Sua definição na JDK é a seguinte:
+. `Supplier` is a functional interface that takes no input parameters but returns a value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Supplier
@@ -29,7 +27,7 @@ public interface Supplier {
}
----
-. Uma implementação possível para um `Supplier` é um gerador da data atual:
+. A possible implementation for a `Supplier` is a current date generator:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_SupplierExample.java
@@ -37,17 +35,17 @@ public interface Supplier {
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_SupplierExample.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-07-08
----
+
-A saída no console irá imprimir a data atual em que este código foi escrito.
+The console output will print the current date this code was written.
+
-Perceba que a expressão lambda está simplificada, sem chaves `{}` ou `return`. Caso tenha dúvidas com relação a isso, consulte novamente a seção sobre expressões lambda.
+Note that the lambda expression is simplified, without `{}` or `return` braces. If you have questions about this, go back again to the section on lambda expressions.
-. Um `Supplier` pode ser utilizado para fornecer uma função custosa em termos de processamento, para que seja chamada apenas se for necessário:
+. A `Supplier` can be used to provide a costly processing function to be called only if needed:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java
@@ -55,16 +53,16 @@ Perceba que a expressão lambda está simplificada, sem chaves `{}` ou `return`.
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Menor de idade!
-Maior de idade! Validação realizada às 2019-07-09T00:21:35.488
+Under age!
+Major age! Validation performed at 2019-07-09T00:21:35.488
----
+
-Perceba que neste caso o supplier só precisou ser chamado na segunda vez, evitando uma execução desnecessária da expressão lambda.
+Note that in this case, the supplier only needed to be called at the second time, avoiding unnecessary execution of the lambda expression.
-. Existem interfaces `Supplier` para lidar tipos primitivos: `BooleanSupplier`, `IntSupplier`, `LongSupplier` e `DoubleSupplier`.
+. There are `Supplier` interfaces for handling primitive types: `BooleanSupplier`, `IntSupplier`, `LongSupplier` and `DoubleSupplier`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java
@@ -72,11 +70,11 @@ Perceba que neste caso o supplier só precisou ser chamado na segunda vez, evita
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java[tag=code]
----
+
-O resultado na console será imprimir o `int` primitivo gerado aleatoriamente.
+The result in the console will be to print the randomly generated primitive `int`.
-===== Consumer e BiConsumer
+===== Consumer and BiConsumer
-. `Consumer` é uma interface funcional que recebe um parâmetro de entrada, e não retorna nenhum valor. Sua definição na JDK é a seguinte:
+. `Consumer` is a functional interface that takes an input parameter, and returns no value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Supplier
@@ -87,7 +85,7 @@ public interface Consumer {
}
----
-. `BiConsumer` é uma interface funcional que recebe dois parâmetros de entrada, e não retorna nenhum valor. Sua definição na JDK é a seguinte:
+. `BiConsumer` is a functional interface that takes two input parameters, and returns no value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Consumer
@@ -98,7 +96,7 @@ public interface BiConsumer {
}
----
-. Implementações possíveis para `Consumer` ou `BiConsumer` são funções que imprimem informações no console:
+. Possible implementations for `Consumer` or` BiConsumer` are functions that print information to the console:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_ConsumerExample.java
@@ -106,7 +104,7 @@ public interface BiConsumer {
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_ConsumerExample.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2019-07-08
@@ -114,7 +112,7 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_ConsumerExam
22:37:39.229
----
-. Existem interfaces `Consumer` para lidar tipos primitivos: `DoubleConsumer`, `IntConsumer`, `LongConsumer`, `ObjDoubleConsumer`, `ObjIntConsumer` e `ObjLongConsumer`.
+. There are `Consumer` interfaces to handle primitive types: `DoubleConsumer`, `IntConsumer`, `LongConsumer`, `ObjDoubleConsumer`, `ObjIntConsumer` and `ObjLongConsumer`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java
@@ -122,9 +120,9 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_ConsumerExam
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java[tag=code]
----
-===== Predicate e BiPredicate
+===== Predicate and BiPredicate
-. `Predicate` é uma interface funcional que recebe um parâmetro de entrada e retorna um valor booleano. Sua definição na JDK é a seguinte:
+. `Predicate` is a functional interface that takes an input parameter and returns a boolean value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Predicate
@@ -135,7 +133,7 @@ public interface Predicate {
}
----
-. `BiPredicate` é uma interface funcional que recebe dois parâmetros de entrada e retorna um valor booleano. Sua definição na JDK é a seguinte:
+. `BiPredicate` is a functional interface that takes two input parameters and returns a boolean value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.BiPredicate
@@ -146,7 +144,7 @@ public interface BiPredicate {
}
----
-. Implementações possíveis para `Predicate` ou `BiPredicate` são funções que verificam se o valor de entrada é igual ao valor sorteado:
+. Possible implementations for `Predicate` or `BiPredicate` are functions that check whether the input value is equal to the raffled value:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_PredicateExample.java
@@ -154,9 +152,9 @@ public interface BiPredicate {
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_PredicateExample.java[tag=code]
----
+
-A saída no console é aleatória, pois depende do valor sorteado. Um valor possível seria `false` e `true`.
+The output on the console is random as it depends on the amount raffled. A possible value would be `false` and `true`.
-. Existem interfaces `Predicate` para lidar tipos primitivos: `DoublePredicate`, `IntPredicate` e `LongPredicate`.
+. There are `Predicate` interfaces for handling primitive types: `DoublePredicate`, `IntPredicate` and `LongPredicate`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java
@@ -164,9 +162,9 @@ A saída no console é aleatória, pois depende do valor sorteado. Um valor poss
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java[tag=code]
----
-===== Function e BiFunction
+===== Function and BiFunction
-. `Function` é uma interface funcional que recebe um parâmetro de entrada e retorna um valor. Sua definição na JDK é a seguinte:
+. `Function` is a functional interface that takes an input parameter and returns a value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Function
@@ -177,7 +175,7 @@ public interface Function {
}
----
-. `BiFunction` é uma interface funcional que recebe dois parâmetros de entrada e retorna um valor. Sua definição na JDK é a seguinte:
+. `BiFunction` is a functional interface that takes two input parameters and returns a value. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.BiFunction
@@ -188,7 +186,7 @@ public interface BiFunction {
}
----
-. Implementações possíveis para `Function` ou `BiFunction` são funções que multiplicam os valores fornecidos:
+. Possible implementations for `Function` or `BiFunction` are functions that multiply the given values:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_FunctionExample.java
@@ -196,14 +194,14 @@ public interface BiFunction {
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_FunctionExample.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
7.5
30.0
----
-. Existem várias interfaces `Function` para lidar tipos primitivos: `DoubleFunction`, `DoubleToIntFunction`, `DoubleToLongFunction`, `IntFunction`, `IntToDoubleFunction`, `IntToLongFunction`, `LongFunction`, `LongToDoubleFunction`, `LongToIntFunction`, `ToDoubleBiFunction`, `ToDoubleFunction`, `ToIntBiFunction`, `ToIntFunction`, `ToLongBiFunction`, `ToLongFunction`.
+. There are several `Function` interfaces for handling primitive types: `DoubleFunction`, `DoubleToIntFunction`, `DoubleToLongFunction`, `IntFunction`, `IntToDoubleFunction`, `IntToLongFunction`, `LongFunction`, `LongToDoubleFunction`, `LongToIntFunction`, `ToDoubleBiFunction`, `ToDoubleFunction`, `ToIntBiFunction`, `ToIntFunction`, `ToLongBiFunction`, `ToLongFunction`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java
@@ -211,16 +209,16 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_FunctionExam
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
7.5
30.0
----
-===== UnaryOperator e BinaryOperator
+===== UnaryOperator and BinaryOperator
-. `UnaryOperator` é uma interface funcional que recebe um parâmetro de entrada e retorna um valor do mesmo tipo da entrada. Sua definição na JDK é a seguinte:
+. `UnaryOperator` is a functional interface that takes an input parameter and returns a value of the same type as the input. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.Function
@@ -231,9 +229,9 @@ public interface UnaryOperator extends Function {
}
----
+
-Perceba que não existe método abstrato declarado, pois ela apenas estende a interface `Function` já existente.
+Note that there is no declared abstract method as it only extends the existing `Function` interface.
-. `BinaryOperator` é uma interface funcional que recebe dois parâmetros de entrada do mesmo tipo, e retorna um valor do mesmo tipo das entradas. Sua definição na JDK é a seguinte:
+. `BinaryOperator` is a functional interface that takes two input parameters of the same type, and returns a value of the same type as the inputs. Its definition in JDK is as follows:
+
[source,java]
.java.util.function.BiFunction
@@ -244,9 +242,9 @@ public interface BinaryOperator extends BiFunction {
}
----
+
-Perceba que não existe método abstrato declarado, pois ela apenas estende a interface `BiFunction` já existente.
+Note that there is no declared abstract method as it only extends the existing `BiFunction` interface.
-. Implementações possíveis para `UnaryOperator` ou `BinaryOperator` são funções que soma um número fixo ou soma um número ao outro:
+. Possible implementations for `UnaryOperator` or `BinaryOperator` are functions that add a fixed number or add one number to another:
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OperatorExample.java
@@ -254,14 +252,14 @@ Perceba que não existe método abstrato declarado, pois ela apenas estende a in
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OperatorExample.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
9
6
----
-. Existem interfaces `Operator` para lidar tipos primitivos: `DoubleBinaryOperator`, `DoubleUnaryOperator`, `IntBinaryOperator`, `IntUnaryOperator`, `LongBinaryOperator`, `LongUnaryOperator`.
+. There are `Operator` interfaces to handle primitive types: `DoubleBinaryOperator`, `DoubleUnaryOperator`, `IntBinaryOperator`, `IntUnaryOperator`, `LongBinaryOperator`, `LongUnaryOperator`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java
@@ -269,7 +267,7 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OperatorExam
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
9
@@ -278,12 +276,12 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OperatorPrim
==== Optional
-O Java 8 possui um tipo específico para representar valores que podem não ter sido informados, que é a classe `Optional`. A partir do Java 8, ela geralmente é uma opção melhor do que retornar ou armazenar `null`, pois seus métodos auxiliam em várias situações.
+Java 8 has a specific type to represent values that may not have been entered, which is the `Optional` class. Starting with Java 8, it is often a better option than returning or storing `null`, as its methods help in many situations.
-. É possível criar uma instância de `Optional` com valor através do método `of`.
-. É possível criar uma instância de `Optional` sem valor através do método `empty`.
-. É possível checar se uma instância de `Optional` possui um valor através do método `isPresent`.
-. É possível recuperar o valor de uma instância de `Optional` através do método `get`.
+. You can create an instance of `Optional` with value through the `of` method.
+. You can create a worthless instance of `Optional` using the `empty` method.
+. You can check if an instance of `Optional` has a value through the `isPresent` method.
+. You can retrieve the value of an instance of `Optional` through the `get` method.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalCreation.java
@@ -291,7 +289,7 @@ O Java 8 possui um tipo específico para representar valores que podem não ter
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalCreation.java[tag=code]
----
-. Não é possível chamar o método `of` passando `null` como argumento. Para isso existe o método `ofNullable`.
+. It is not possible to call the `of` method by passing `null` as an argument. For this there is the `ofNullable` method.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalNullable.java
@@ -299,7 +297,7 @@ include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalCrea
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalNullable.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
java.lang.NullPointerException
@@ -310,7 +308,7 @@ java.lang.NullPointerException
false
----
-. Com o método `ifPresent` é possível executar uma expressão lambda apenas se o `Optional` tiver valor.
+. With the `ifPresent` method you can execute a lambda expression only if `Optional` has value.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java
@@ -318,13 +316,13 @@ false
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Com Valor: valor
+With Value: value
----
-. É possível recuperar um valor padrão caso o `Optional` esteja vazio. O método `orElse` retorna um valor diretamente, e o `orElseGet` retorna através de uma expressão lambda.
+. You can retrieve a default value if `Optional` is empty. The `orElse` method returns a value directly, and `orElseGet` returns via a lambda expression.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java
@@ -332,18 +330,18 @@ Com Valor: valor
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-valor padrao
-valor padrao
-valor
-valor
+default value
+default value
+value
+value
----
+
-TIP: Observe que esse é um ótimo caso para lembrar de um benefício das expressões lambda. Na utilização de `orElseGet` a expressão lambda só é executada caso o `Optional` esteja vazio. No caso do exemplo, como é apenas o retorno de uma `String`, não faz diferença. Porém, se fosse uma operação mais pesada, você só iria de fato executá-la se o `Optional` estivesse vazio. Caso houvesse valor, a expressão lambda nem seria executada, evitando o custo de processamento.
+TIP: Note that this is a great case for remembering a benefit of lambda expressions. When using `orElseGet` the lambda expression is only executed if `Optional` is empty. In the case of the example, as it is only the return of a `String`, it makes no difference. However, if it were a heavier operation, you would only actually perform it if `Optional` was empty. If there was value, the lambda expression would not even be executed, avoiding the processing cost.
-. Também é possível lançar uma exceção caso um valor não esteja presente no `Optional` utilizando o método `orElseThrow`.
+. You can also throw an exception if a value is not present in `Optional` using the `orElseThrow` method.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java
@@ -351,17 +349,17 @@ TIP: Observe que esse é um ótimo caso para lembrar de um benefício das expres
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-valor
+value
Exception in thread "main" java.lang.RuntimeException
- at org.j6toj8.lambda.builtininterfaces.BuiltInInterfaces_OptionalOrElseThrow.lambda$1(BuiltInInterfaces_OptionalOrElseThrow.java:17)
+ at org.j6toj8.lambda.builtininterfaces.BuiltInInterfaces_OptionalOrElseThrow.lambda$main$1(BuiltInInterfaces_OptionalOrElseThrow.java:17)
at java.util.Optional.orElseThrow(Optional.java:290)
at org.j6toj8.lambda.builtininterfaces.BuiltInInterfaces_OptionalOrElseThrow.main(BuiltInInterfaces_OptionalOrElseThrow.java:17)
----
-. Será lançada uma exceção ao chamar o método `get` em um `Optional` vazio.
+. An exception will be thrown when calling the `get` method on an empty `Optional`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java
@@ -369,17 +367,16 @@ Exception in thread "main" java.lang.RuntimeException
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-valor
+value
Exception in thread "main" java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at org.j6toj8.lambda.builtininterfaces.BuiltInInterfaces_OptionalGetEmpty.main(BuiltInInterfaces_OptionalGetEmpty.java:13)
----
-
-. Existem algumas classes para lidar com valor opcionais de variáveis primitivas, já que elas não podem ser utilizada com `generics`: `OptionalInt`, `OptionalDouble`, `OptionalLong`.
+. There are some classes for dealing with optional value of primitive variables, as they cannot be used with `generics`: `OptionalInt`, `OptionalDouble`, `OptionalLong`.
+
[source,java,indent=0]
.{java-package}/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java
@@ -387,18 +384,18 @@ Exception in thread "main" java.util.NoSuchElementException: No value present
include::{section-java-package}/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
5
----
-.Referências
+.References
****
* Working with Built-In Functional Interfaces
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 173). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 173). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-functional-interfaces[Functional Interfaces in Java 8.]
@@ -410,4 +407,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* http://eherrera.net/ocpj8-notes/04-lambda-built-in-functional-interfaces[Lambda Built-in Functional Interfaces.]
-****
\ No newline at end of file
+****
diff --git a/book/04-lambda/sections/04-method-reference.asc b/book/04-lambda/sections/04-method-reference.asc
index 47c979a..9f4b62c 100644
--- a/book/04-lambda/sections/04-method-reference.asc
+++ b/book/04-lambda/sections/04-method-reference.asc
@@ -2,29 +2,27 @@
:java-package: src/org/j6toj8/lambda
:section-java-package: ../../../{java-package}
-=== Referências a Métodos (Method Reference)
+=== Method Reference
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses a method reference, including refactoring a lambda expression to a method reference.
--
-Desenvolver código que utiliza uma referência a método, incluindo a refatoração de uma expressão lambda para uma referência a método.
--------------------------------------------------
-A sintaxe de referência a um método é uma novidade do Java 8. Com ela é possível fazer referência a métodos específicos, em quatro ocasições diferentes:
+The reference syntax for a method is new to Java 8. With it you can reference specific methods on four different occasions:
-* Referências a métodos estáticos -> `String::valueOf`
-* Referências a métodos de um objeto -> `instanciaDeString::isEmpty`
-* Referências a métodos de um tipo de objeto (de uma classe, interface, etc) -> `String::isEmpty`
-* Referências a construtores -> `String::new`
+* Static Method References -> `String::valueOf`
+* Method references of an object -> `instanceString::isEmpty`
+* References to methods of an object type (of a class, interface, etc.) -> `String::isEmpty`
+* Constructor References -> `String::new`
-É essencial lembrar das Interfaces Funcionais, das variações de sintaxe de Expressões Lambda e das definições de Interfaces Funcionais Pré-Construídas. Caso julgue necessário, reveja as seções deste capítulo.
+It is essential to remember Functional Interfaces, Lambda Expression syntax variations, and Built-in Interfaces definitions. If necessary, review the sections in this chapter.
-É possível pensar nas referências a métodos como uma outra forma de escrever uma expressão lambda, caso a única coisa que sua expressão lambda faça seja chamar um outro método.
+You can think of method references as another way to write a lambda expression if the only thing your lambda expression does is call another method.
-A seguir serão apresentadas as ocasiões em que são utilizadas as referências a métodos.
+The following are the occasions when method references are used.
-. Chamadas a métodos estáticos em expressões lambda podem virar uma referência ao método.
+. Calls to static methods in lambda expressions can become a reference to the method.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Static.java
@@ -32,22 +30,22 @@ A seguir serão apresentadas as ocasiões em que são utilizadas as referências
include::{section-java-package}/methodreference/MethodReference_Static.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
5
5
----
+
-Nesse caso a única coisa que a expressão lambda faz é receber um argumento `x` e repassar para o método `valueOf` de `String`. Para simplificar isso, o Java 8 permite que você escreva essa mesma função lambda como foi apresentado na linha seguinte: `String::valueOf`.
+In this case the only thing the lambda expression does is take an `x` argument and pass it to the `String` `valueOf` method. To simplify this, Java 8 allows you to write this same lambda function as presented on the following line: `String::valueOf`.
+
-Só é possível representar a primeira expressão lambda na forma de um _method reference_ porque:
+You can only represent the first lambda expression in the form of a _method reference_ because:
+
-* A implementação de `String.valueOf` satisfaz a interface funcional `Function` (recebe um argumento e retorna um valor).
-* O argumento de entrada da expressão lambda `x` é exatamente o mesmo passado para o método `String.valueOf(x)`.
-* A expressão lambda é simples: somente possui uma chamada a um método.
+* The implementation of `String.valueOf` satisfies the `Function` functional interface (takes an argument and returns a value).
+* The input argument of the lambda `x` expression is exactly the same as that passed to the `String.valueOf(x)` method.
+* The lambda expression is simple: it only has one method call.
-. Chamadas a métodos de uma instância específica também podem ser representados como uma referência a um método.
+. Method calls from a specific instance can also be represented as a reference to a method.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Instance.java
@@ -55,20 +53,20 @@ Só é possível representar a primeira expressão lambda na forma de um _method
include::{section-java-package}/methodreference/MethodReference_Instance.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
5 - 8
5 - 8
----
+
-Só é possível representar a primeira expressão lambda na forma de um _method reference_ porque:
+You can only represent the first lambda expression in the form of a _method reference_ because:
+
-* A implementação de `Conversor.converte(Integer, Integer)` satisfaz a interface funcional `BiFunction` (recebe dois argumentos e retorna um valor).
-* Os argumentos de entrada da expressão lambda `x` e `y` são exatamente os mesmos passados para o método `Conversor.converte(Integer, Integer)`.
-* A expressão lambda é simples: somente possui uma chamada a um método.
+* The implementation of `Converter.convert(Integer, Integer)` satisfies the `BiFunction` functional interface (takes two arguments and returns a value).
+* The input arguments of the lambda expression `x` and `y` are exactly the same as those passed to the `Converter.convert(Integer, Integer)` method.
+* The lambda expression is simple: it only has one method call.
-. Chamadas a métodos de uma classe, sem especificar a instância específica, também podem ser representados como uma referência a um método.
+. Calls to methods of a class, without specifying the specific instance, can also be represented as a reference to a method.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Type.java
@@ -76,20 +74,20 @@ Só é possível representar a primeira expressão lambda na forma de um _method
include::{section-java-package}/methodreference/MethodReference_Type.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
8.0
8.0
----
+
-Nesse exemplo, a referência está sendo feita ao método `doubleValue` do *tipo* `Integer`. Só é possível representar a primeira expressão lambda na forma de um _method reference_ porque:
+In this example, reference is being made to the `doubleValue` method of `Integer` *type*. You can only represent the first lambda expression in the form of a _method reference_ because:
+
-* Nossa expressão lambda satisfaz a interface funcional `Function` (recebe um argumento `x` e retorna um valor `double`).
-* A expressão lambda recebe um argumento `x` do tipo `Integer`, que possui o método `doubleValue` que não recebe parâmetros.
-* A expressão lambda é simples: somente possui uma chamada a um método.
+* Our lambda expression satisfies the `Function` functional interface (takes an `x` argument and returns a `double` value).
+* The lambda expression takes an `x` argument of `Integer` type, which has the `doubleValue` method that takes no parameters.
+* The lambda expression is simple: it only has one method call.
-. Também é possível utilizar a referência ao método de um tipo, como no exemplo anterior, mesmo que o método receba parâmetros.
+. You can also use the method reference of a type, as in the previous example, even if the method receives parameters.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_TypeWithParam.java
@@ -97,16 +95,16 @@ Nesse exemplo, a referência está sendo feita ao método `doubleValue` do *tipo
include::{section-java-package}/methodreference/MethodReference_TypeWithParam.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-1
-1
----
+
-Nesse exemplo o compilador "descobre" ainda mais coisas que nos exemplos anteriores. Ao escrever apenas a referência ao método, o compilador entende que a variável `x`, que vem primeiro, será a instância de `Integer` onde o método `compareTo` será chamado. E que `y` é a instância de `Integer` que será passada como argumento para o método `compareTo`.
+In this example the compiler "discovers" even more things than in the previous examples. By writing only the method reference, the compiler understands that the `x` variable, which comes first, will be the instance of `Integer` where the `compareTo` method will be called. And that `y` is the instance of `Integer` that will be passed as an argument to the `compareTo` method.
-. Chamadas a um construtor também podem ser representadas como uma referência a um método.
+. Calls to a constructor can also be represented as a reference to a method.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Constructor.java
@@ -114,16 +112,16 @@ Nesse exemplo o compilador "descobre" ainda mais coisas que nos exemplos anterio
include::{section-java-package}/methodreference/MethodReference_Constructor.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
1
1
----
+
-Esse exemplo é muito parecido com o anterior, com a única diferença sendo que o método referenciado é um construtor. Perceba que o construtor também recebe um parâmetro e, assim como no exemplo anterior, o compilador entende que o argumento da função lambda deve ser passado para o construtor que foi chamado.
+This example is very similar to the previous one, with the only difference being that the referenced method is a constructor. Note that the constructor also gets a parameter and, as in the previous example, the compiler understands that the lambda function argument must be passed to the called constructor.
-. Expressões lambda complexas não podem ser convertidas em referência a método, como a expressão abaixo:
+. Complex lambda expressions cannot be converted to method references, like the expression below:
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Complex.java
@@ -131,9 +129,9 @@ Esse exemplo é muito parecido com o anterior, com a única diferença sendo que
include::{section-java-package}/methodreference/MethodReference_Complex.java[tag=code]
----
+
-Como nesse caso temos uma outra `String` `+ "2"` sendo acrescentada no construtor, não há como representar isso com uma simples referência ao construtor.
+Since in this case we have another `String` `+ "2"` being added to the constructor, there is no way to represent this with a simple reference to the constructor.
-. É possível utilizar _method reference_ também com suas própria classes. Veja no exemplo a seguir os tipos criados pelo nosso código e as expressões lambda equivalentes com e sem referência a métodos.
+. You can use _method reference_ also with your own classes. See the following example for types created by our code and equivalent lambda expressions with and without reference to methods.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_CustomType.java
@@ -141,15 +139,15 @@ Como nesse caso temos uma outra `String` `+ "2"` sendo acrescentada no construto
include::{section-java-package}/methodreference/MethodReference_CustomType.java[tag=code]
----
+
-Perceba a diferença entre as expressões lambda:
+Note the difference between lambda expressions:
+
-* Uma parte implementa a interface functional `Function`, pois recebem um argumento e retornam um valor.
+* One part implements the `Function` functional interface, as they take an argument and return a value.
+
-* A última implementa a interface functional `Supplier`, pois não recebe argumento, mas retorna um valor.
+* The latter implements the `Supplier` functional interface, as it does not take an argument, but returns a value.
+
-Em caso de dúvidas, consulte novamente os tipos de interfaces funcionais nas outras seções deste capítulo.
+If in doubt, refer back to the types of functional interfaces in the other sections of this chapter.
-. A variedade de formas para representar uma mesma expressão lambda pode ser grande, então cuidado para não se confundir.
+. The variety of ways to represent the same lambda expression can be large, so be careful not to get confused.
+
[source,java,indent=0]
.{java-package}/methodreference/MethodReference_Variaty.java
@@ -157,17 +155,17 @@ Em caso de dúvidas, consulte novamente os tipos de interfaces funcionais nas ou
include::{section-java-package}/methodreference/MethodReference_Variaty.java[tag=code]
----
+
-Você já viu todas as formas de criar uma expressão lambda, desde a mais completa até a mais simples. Tenha certeza que conhece todas essas variações para o exame de certificação.
+You have seen all the ways to create a lambda expression, from the most complete to the simplest. Make sure you know all these variations for the certification exam.
-.Referências
+.References
****
* Using Method References
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 152). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 152). Wiley. Kindle Edition.
* https://www.baeldung.com/java-method-references[Method References in Java.]
* https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html[Method References.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/05-java-streams/sections/01-using-streams.asc b/book/05-java-streams/sections/01-using-streams.asc
index 82d8d36..74ebac4 100644
--- a/book/05-java-streams/sections/01-using-streams.asc
+++ b/book/05-java-streams/sections/01-using-streams.asc
@@ -1,25 +1,22 @@
:java-package: src/org/j6toj8/streams
:section-java-package: ../../../{java-package}
-=== Utilizando Streams
+=== Using Streams
-.Objetivo
+.Objective
--------------------------------------------------
Describe the Stream interface and pipelines; create a stream by using the Arrays.stream() and IntStream.range() methods; identify the lambda operations that are lazy.
--
-Descrever a interface e pipelines de Stream; criar um stream utilizando os métodos Arrays.stream() e IntStream.range(); identificar quais operações lambda executam sob demanda (_lazy_).
--------------------------------------------------
-Uma das maiores novidades do Java 8 são os _Streams_. Um _Stream_ é basicamente um fluxo de dados.
-Os dados podem ser _Strings_, números, ou qualquer outro objeto. Esses dados passam por uma série de operações, e o conjunto dessas operações é chamado de _pipeline_. Essas operações são quase sempre representadas por expressões lambda, então é muito importante ter dominado todo o capítulo sobre *lambda*, pois todos aqueles conceitos serão utilizados agora para formar um _Stream_.
+One of the biggest things about Java 8 is _Streams_. A _Stream_ is a data stream. The data can be _Strings_, numbers, or any other object. This data goes through a series of operations, and the set of these operations is called _pipeline_. Lambda expressions almost always represent these operations. So it is essential to have mastered the whole chapter on *lambda*, as all those concepts will now be used to form a _Stream_.
-A partir dos exemplos a seguir, essa explicação ficará mais clara.
+From the following examples, this explanation will become more evident.
-==== Criando um _Stream_
+==== Creating a _Stream_
-Geralmente, um _Stream_ é criado a partir de um conjunto de dados, como uma lista ou outro tipo de coleção. O objeteivo da certificação deixa explícito que é necessário conhecer os métodos `Arrays.stream()` e `IntStream.range()`. Mas, além dessas, serão apresentadas também algumas outras formas comuns de criar um _Stream_.
+Typically, a _Stream_ is created from a dataset, such as a list or other collection type. The purpose of the certification makes explicit that it is necessary to know the `Arrays.stream()` and `IntStream.range()` methods. But in addition to these, some other common ways to create a _Stream_ will be presented.
-. É possível criar um Stream a partir de um `Array` utilizando o método `Arrays.stream()`.
+. You can create a stream from an `Array` using the `Arrays.stream()` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/Stream_ArraysStream.java
@@ -27,7 +24,7 @@ Geralmente, um _Stream_ é criado a partir de um conjunto de dados, como uma lis
include::{section-java-package}/usingstreams/Streams_ArraysStream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -35,7 +32,7 @@ B
C
----
-. É possível criar um Stream a partir de uma faixa de números utilizando o método `IntStream.range()`.
+. You can create a stream from a number range using the `IntStream.range()` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/Stream_IntRangeStream.java
@@ -43,7 +40,7 @@ C
include::{section-java-package}/usingstreams/Streams_IntRangeStream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
0
@@ -52,9 +49,9 @@ include::{section-java-package}/usingstreams/Streams_IntRangeStream.java[tag=cod
3
----
+
-Perceba que o primeiro argumento (número 0) é inclusivo, enquanto o segundo argumento (número 4) é exclusivo. Por isso a saída no console apresenta apenas os números 0 a 3.
+Note that the first argument (number 0) is inclusive, while the second argument (number 4) is exclusive. Therefore the console output has only the numbers 0 to 3.
-. É possível criar um _Stream_ a partir de uma lista.
+. You can create a _Stream_ from a list.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_ListStream.java
@@ -62,7 +59,7 @@ Perceba que o primeiro argumento (número 0) é inclusivo, enquanto o segundo ar
include::{section-java-package}/usingstreams/Streams_ListStream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -70,7 +67,7 @@ B
C
----
-. É possível criar um _Stream_ a partir de elementos específicos utilizando o método `Stream.of`.
+. You can create a _Stream_ from specific elements using the `Stream.of` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Of.java
@@ -78,7 +75,7 @@ C
include::{section-java-package}/usingstreams/Streams_Of.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -89,15 +86,15 @@ B
4.0
----
+
-Nesse caso foi criado um _Stream_ que contém: `String`, `Character`, `Integer`, `Long`, `Float` e `Double`.
+In this case a _Stream_ was created that contains: `String`, `Character`, `Integer`,`Long`, `Float` and `Double`.
-==== Operações em _Streams_
+==== _Streams_ operations
-As operações feitas em um _Stream_ irão formar seu _pipeline_. As operações que podem ser realizadas em um Stream são divididas em *operações intermediárias* e **operações finais**. O _Stream_ pode conter inúmeras operações intermediárias, porém somente uma final. Nos exemplos anteriores a única operação utilizada foi o `forEach`, que é uma operação final. A seguir serão apresentadas outras operações.
+Operations done on a _Stream_ will form its _pipeline_. Operations that can be performed on a Stream are divided into *Intermediate Operations* and *Final Operations*. _Stream_ can contain numerous intermediate operations, but only one final operation. In the previous examples the only operation used was `forEach`, which is a final operation. Other operations will be presented below.
-===== Operações intermediárias
+===== Intermediate Operations
-. É possível ignorar elementos de um stream com a operaçao `skip`.
+. You can ignore elements of a stream with the `skip` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Stream_Skip.java
@@ -105,16 +102,16 @@ As operações feitas em um _Stream_ irão formar seu _pipeline_. As operações
include::{section-java-package}/usingstreams/Streams_Skip.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2
3
----
+
-Perceba que nesse caso os elementos 0 e 1 foram ignorados, pois são os dois primeiros elementos do _Stream_. Isso ocorreu pela existência da operação `skip`.
+Note that in this case elements 0 and 1 were ignored, as they are the first two elements of _Stream_. This was due to the existence of the `skip` operation.
-. É possível limitar a quantidade de elementos que serão processados utilizando a operação `limit`.
+. You can limit the amount of elements that will be processed using the `limit` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Limit.java
@@ -122,16 +119,16 @@ Perceba que nesse caso os elementos 0 e 1 foram ignorados, pois são os dois pri
include::{section-java-package}/usingstreams/Streams_Limit.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
0
1
----
+
-Nesse caso apenas os 2 primeiros elementos foram impressos no console, pois a operação `limit` limitou a quantidade de elementos a serem processados.
+In this case only the first 2 elements were printed on the console because the `limit` operation limited the amount of elements to be processed.
-. É possível filtrar elementos do `Stream` utilizando a operação `filter`.
+. You can filter `Stream` elements using the `filter` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Filter.java
@@ -139,16 +136,16 @@ Nesse caso apenas os 2 primeiros elementos foram impressos no console, pois a op
include::{section-java-package}/usingstreams/Streams_Filter.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
0
2
----
+
-Nesse caso apenas os elementos pares foram impressos, pois a operação `filter` limitou àqueles que possuem resto da divisão por 2 igual a 0.
+In this case only the even elements were printed, as the `filter` operation limited to those that have remainder division by 2 equal to 0.
-. É possível filtrar elementos repetidos do _Stream_ utilizando a operação `distinct`.
+. You can filter out repeated _Stream_ elements using the `distinct` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Distinct.java
@@ -156,7 +153,7 @@ Nesse caso apenas os elementos pares foram impressos, pois a operação `filter`
include::{section-java-package}/usingstreams/Streams_Distinct.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -165,11 +162,11 @@ C
F
----
+
-Perceba que nesse caso os elementos repetidos do stream (`"A"` e `"B"`) foram ignorados, sendo apresentados apenas uma vez.
+Note that in this case the repeated stream elements (`"A"` and `"B"`) were ignored and only presented once.
+
-A operação `distinct` utiliza os método `equals` e `hashCode`, então tenha certeza de que eles estão implementados corretamente caso esteja utilizando um tipo de objeto criado por você. No exemplo foram utilizados objetos do tipo `String`, que já possuem essa implementação por padrão.
+The `distinct` operation uses the `equals` and `hashCode` methods, so make sure they are implemented correctly if you are using an object type that you create. In the example were used objects of type `String`, which already have this implementation by default.
-. É possível aplicar uma transformação nos elementos do Stream utilizando a operação `map`.
+. You can apply a transformation to Stream elements using the `map` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Map.java
@@ -177,7 +174,7 @@ A operação `distinct` utiliza os método `equals` e `hashCode`, então tenha c
include::{section-java-package}/usingstreams/Streams_Map.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
0
@@ -186,9 +183,9 @@ include::{section-java-package}/usingstreams/Streams_Map.java[tag=code]
6
----
+
-Perceba que nesse caso os elementos sofreram uma transformação, que foi a multiplicação por 2, antes de serem impressos no console.
+Note that in this case, the elements underwent a transformation, which was multiplication by 2 before being printed on the console.
-. É possível ordenar os elementos de um Stream utilizando a operação `sorted`.
+. You can sort the elements of a Stream using the `sorted` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Sorted.java
@@ -196,7 +193,7 @@ Perceba que nesse caso os elementos sofreram uma transformação, que foi a mult
include::{section-java-package}/usingstreams/Streams_Sorted.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -210,9 +207,9 @@ T
Y
----
+
-Nesse caso todos os elementos são ordenados utilizando a ordem natural dos objetos `String`, pois eles já implementam a interface `Comparable`, sendo apresentados em ordem alfabética. Também existe uma versão do método `sort` que recebe como argumento uma implementação de `Comparator`, caso deseje ordenar de outra forma.
+In this case, all elements are sorted using the natural order of the `String` objects, as they already implement the `Comparable` interface and are presented in alphabetical order. There is also a version of the `sort` method that takes as its argument an implementation of `Comparator` if you want to sort it otherwise.
-. É possível observar os elementos que passam por um _Stream_ utilizando a operação `peek`.
+. You can observe the elements passing through a _Stream_ using the `peek` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Peek.java
@@ -220,7 +217,7 @@ Nesse caso todos os elementos são ordenados utilizando a ordem natural dos obje
include::{section-java-package}/usingstreams/Streams_Peek.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Peek: G
@@ -233,9 +230,9 @@ Peek: A
ForEach: A
----
+
-A operação `peek` funciona apenas para observar o que está passando pelo _Stream_. Pode ser muito útil para realizar _debug_ ou _log_. Nesse caso os elementos estão sendo impressos duas vezes no console, pois o método `peek` e o `forEach` estão ambos realizando essa mesma ação. Porém, em aplicações reais, geralmente a operação final *não* será um `forEach`, de tal forma que fará sentido utilizar o `peek`.
+The `peek` operation works only to observe what is going through _Stream_. It can be very useful for performing _debug_ or _log_. In this case, the elements are being printed twice on the console because the `peek` and `forEach` methods are both doing the same action. However, in real applications, usually the final operation *will not* be a `forEach`, so it will make sense to use `peek`.
-. É possível transformar um _Stream_ de vários `Arrays` em um único _Stream_ *contínuo* utilizando o método `flatMap`.
+. You can transform a _Stream_ from multiple `Arrays` into a single *continuous* _Stream_ using the `flatMap` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_FlatMap.java
@@ -243,7 +240,7 @@ A operação `peek` funciona apenas para observar o que está passando pelo _Str
include::{section-java-package}/usingstreams/Streams_FlatMap.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
@@ -257,13 +254,13 @@ H
I
----
+
-Perceba que nesse caso existem 3 `Arrays` distintos. Então cria-se um _Stream_ contendo 3 `Arrays`. O cenário comum seria um que cada elemento do _Stream_ fosse um objeto do tipo `Array`. Porém, ao utilizar a operação `flatMap`, é criado um _Stream_ para cada um desses `Arrays`, que são unidos e formam um único _Stream_ contínuo.
+Note that in this case there are 3 distinct `Arrays`. Then create a _Stream_ containing 3 `Arrays`. The typical scenario would be that each _Stream_ element was an `Array` object. However, using the `flatMap` operation, a _Stream_ is created for each of these `Arrays`, which are joined and form a single continuous _Stream_.
-===== Operações finais
+===== Final operations
-. É possível executar uma ação final para cada elemento do _Stream_ utilizando a operação `forEach`, conforme demonstrado nos exemplos anteriores.
+. You can perform a final action for each _Stream_ element using the `forEach` operation, as shown in the previous examples.
-. É possível recuperar o maior e o menor valor de um _Stream_ utilizando as operações finais `max` e `min`. E também é possível recuperar a quantidade de elementos de um _Stream_ utilizando a operação final `count`.
+. You can retrieve the largest and smallest value of a _Stream_ using the `max` and `min` final operations. And it is also possible to retrieve the number of elements of a _Stream_ using the `count` final operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_MaxMinCount.java
@@ -271,7 +268,7 @@ Perceba que nesse caso existem 3 `Arrays` distintos. Então cria-se um _Stream_
include::{section-java-package}/usingstreams/Streams_MaxMinCount.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Max: 9
@@ -279,11 +276,11 @@ Min: 1
Count: 8
----
+
-No caso das operações `max` e `min`, é necessário passar como argumento qual comparador será utilizado. Como os números possuem uma ordem natural, isto é, implementam a interface `Comparable`, é possível utilizar um comparador que usa essa ordem natural, que é o `Comparator.naturalOrder()`. Caso seja um tipo de objeto que não possui uma ordem natural, é necessário passar como argumento uma outra implementação de `Comparator`.
+For `max` and `min` operations, it is necessary to pass as an argument which comparator will be used. Since numbers have a natural order, that is, they implement the `Comparable` interface, it is possible to use a comparator that uses that natural order, which is `Comparator.naturalOrder()`. If it is a type of object that does not have a natural order, it is necessary to pass another implementation of `Comparator` as an argument.
+
-As operações `max` e `min` retornam `Optional` pois, caso o _Stream_ esteja vazio, será um `Optional` vazio. Desde o Java 8, com a adição da classe `Optional`, isso tem sido preferido ao invés de retornar `null`, pois facilita a programação funcional. A operação `count` não precisa de um `Optional`, pois mesmo com um _Stream_ vazio irá retornar `0`.
+The `max` and `min` operations return `Optional` because if _Stream_ is empty it will be empty `Optional`. Since Java 8, with the addition of the `Optional` class, this has been preferred over returning `null` as it facilitates functional programming. The `count` operation does not need an `Optional`, because even with an empty _Stream_ will return `0`.
-. É possível pegar o primeiro elemento do Stream utilizando a operação final `findFirst`, ou um elemento qualquer com `findAny`.
+. You can get the first element of the Stream using the final `findFirst` operation, or any element with `findAny`.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_FindFirstAny.java
@@ -291,18 +288,18 @@ As operações `max` e `min` retornam `Optional` pois, caso o _Stream_ esteja va
include::{section-java-package}/usingstreams/Streams_FindFirstAny.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
First: 7
Any: 7
----
+
-Nesse caso, como o _Stream_ é sequencial e não paralelo, os dois resultados são iguais. Em _Streams_ paralelos, que serão apresentados em uma próxima seção, a operação `findAny` pode trazer resultados diferentes.
+In this case, because _Stream_ is sequential and not parallel, both results are equal. In parallel _Streams_, which will be presented in another section, the `findAny` operation may yield different results.
+
-Assim como as operações `max` e `min` apresentadas anteriormente, `findAny` e `findFirst` retornam um `Optional` vazio caso o _Stream_ esteja vazio.
+Like the `max` and `min` operations presented earlier, `findAny` and `findFirst` return an empty `Optional` if _Stream_ is empty.
-. É possível verificar se os elementos do _Stream_ atendem a alguma validação utilizando as operações finais `allMatch`, `anyMatch` e `noneMatch`.
+. You can verify that _Stream_ elements meet some validation by using the `allMatch`, `anyMatch`, and `noneMatch` final operations.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Match.java
@@ -310,7 +307,7 @@ Assim como as operações `max` e `min` apresentadas anteriormente, `findAny` e
include::{section-java-package}/usingstreams/Streams_Match.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
anyMatch: true
@@ -318,9 +315,9 @@ allMatch: false
noneMatch: false
----
+
-Perceba que na primeira operação é verificado se *qualquer* elemento é maior do que 5. Na segunda, se *todos* os elementos são maiores do que 5. E na terceira, se *nenhum* elemento é maior do que 5.
+Note that in the first operation it is checked that *any* element is greater than 5. In the second, if *all* elements are greater than 5. And in the third, if *no* element is greater than 5.
-. Não é possível chamar mais de uma operação final no mesmo _Stream_.
+. You cannot call more than one final operation on the same _Stream_.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_ReuseStream.java
@@ -328,7 +325,7 @@ Perceba que na primeira operação é verificado se *qualquer* elemento é maior
include::{section-java-package}/usingstreams/Streams_ReuseStream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
7
@@ -342,7 +339,7 @@ Exception in thread "main" java.lang.IllegalStateException: stream has already b
===== Pipeline
-. É possível criar um _pipeline_ com várias operações em um único _Stream_.
+. You can create a _pipeline_ with multiple operations in a single _Stream_.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Pipeline.java
@@ -350,23 +347,23 @@ Exception in thread "main" java.lang.IllegalStateException: stream has already b
include::{section-java-package}/usingstreams/Streams_Pipeline.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
8
12
----
+
-Para entender todas as operações realizadas nesse pipeline, é necessário entender passo a passo:
+To understand all operations performed in this pipeline, you must understand step by step:
+
-.. Foi criado um _Stream_ contendo todos os números de 0 a 9
-.. Foi aplicado um filtro mantendo apenas os números pares: 0, 2, 4, 6 e 8
-.. Foram ignorados os dois primeiros números, mantendo apenas: 4, 6 e 8
-.. Foi limitado o processamento aos dois primeiros números: 4 e 6
-.. Foi aplicada uma multiplicação por 2 em cada elemento, resultando em: 8 e 12
-.. Os dois elementos foram impressos no console.
+.. A _Stream_ was created containing all numbers from 0 to 9.
+.. A filter was applied keeping only the even numbers: 0, 2, 4, 6 and 8.
+.. The first two numbers were ignored, keeping only: 4, 6 and 8.
+.. Processing was limited to the first two numbers: 4 and 6.
+.. Multiplication by 2 was applied to each element, resulting in 8 and 12.
+.. Both elements were printed on the console.
-. O Stream só será criado de fato depois que alguma operação for executada nele.
+. The Stream will only actually be created after any operation has been performed on it.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_ChangeBackingList.java
@@ -374,7 +371,7 @@ Para entender todas as operações realizadas nesse pipeline, é necessário ent
include::{section-java-package}/usingstreams/Streams_ChangeBackingList.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
1
@@ -383,9 +380,9 @@ include::{section-java-package}/usingstreams/Streams_ChangeBackingList.java[tag=
4
----
+
-Perceba que, mesmo que o _Stream_ aparentemente tenha sido criado antes de adicionar o número 4 na lista, ele imprime esse número no console. Isso acontece porque o _Stream_ só foi criado de fato quando alguma operação foi feita nele, ou seja, quando o `forEach` foi invocado.
+Note that even though _Stream_ was apparently created before adding number 4 to the list, it prints this number on the console. This is because _Stream_ was only created when some operation was done on it, i.e., when `forEach` was invoked.
-. É possível encadear a operação final do _Stream_ utilizando expressões lambda na classe `Optional`.
+. You can chain the final _Stream_ operation using lambda expressions in the `Optional` class.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_Optional.java
@@ -393,13 +390,13 @@ Perceba que, mesmo que o _Stream_ aparentemente tenha sido criado antes de adici
include::{section-java-package}/usingstreams/Streams_Optional.java[tag=code]
----
+
-Perceba que o método `ifPresent` é da classe `Optional`, mesmo que no segundo exemplo possa parecer que ele faz parte do _Stream_. Em outras palavras, a operação final é `max`, e `ifPresent` é uma chamada em `Optional` e não mais no _Stream_.
+Note that the `ifPresent` method is from the `Optional` class, even though in the second example, it might look like it is part of _Stream_. In other words, the final operation is `max`, and `ifPresent` is a called in `Optional` and no longer in _Stream_
-===== Execução sob-demanda (_lazy_)
+===== Lazy Invocation
-As operações intermediárias de um _Stream_ só são executadas quando necessário. Ou seja, mesmo que a operação esteja presente no _pipeline_, não é certeza de que ela será executada.
+Intermediate operations of a _Stream_ are only performed when necessary. That is, even if the operation is present in _pipeline_, it is not certain that it will be executed.
-. Nada será feito se o _Stream_ não contiver uma operação final.
+. Nothing will be done if _Stream_ does not contain a final operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_LazyNoFinal.java
@@ -407,9 +404,9 @@ As operações intermediárias de um _Stream_ só são executadas quando necess
include::{section-java-package}/usingstreams/Streams_LazyNoFinal.java[tag=code]
----
+
-Nesse caso nada é impresso no console, pois *nenhuma* operação *final* foi aplicada no _Stream_. Ou seja, se não há nada consumindo o resultado desse _Stream_, o Java nem precisa executar o _pipeline_ criado.
+In this case nothing is printed on the console because *no final operations* were applied to _Stream_. That is, if there is nothing consuming the result of this _Stream_, Java does not have to execute the created _pipeline_.
-. Outras operações intermediárias também não costumam ser executadas se não for necessário.
+. Other intermediate operations are also not usually performed if not required.
+
[source,java,indent=0]
.{java-package}/usingstreams/Streams_LazyMap.java
@@ -417,7 +414,7 @@ Nesse caso nada é impresso no console, pois *nenhuma* operação *final* foi ap
include::{section-java-package}/usingstreams/Streams_LazyMap.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Peek: 0
@@ -428,13 +425,13 @@ Peek: 2
ForEach: 2
----
+
-Perceba que, mesmo que a operação `peek` esteja antes da operação `limit`, ela não é executada para todos os elementos do `Stream`, apenas para aqueles que serão realmente utilizados.
+Note that even if the `peek` operation is before the `limit` operation, it is not performed for all `Stream` elements, only for those that will actually be used.
-==== Streams primitivos
+==== Primitive Streams
-Existem Streams específicos para alguns tipos primitivos como `double`, `int` e `long`. Eles possuem a vantagem de evitar o _Boxing_ e _Unboxing_, fornecendo alguns métodos mais especializados como demonstrado a seguir.
+There are specific streams for some primitive types like `double`, `int` and `long`. They have the advantage of avoiding _Boxing_ and _Unboxing_ by providing some more specialized methods as shown below.
-. É possível criar _Streams_ de tipos primitivos com as classes: `DoubleStream`, `IntStream` e `LongStream`.
+. You can create _Streams_ of primitive types with the classes: `DoubleStream`, `IntStream` and `LongStream`.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_Primitives.java
@@ -442,7 +439,7 @@ Existem Streams específicos para alguns tipos primitivos como `double`, `int` e
include::{section-java-package}/usingstreams/primitives/Streams_Primitives.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
DoubleStream
@@ -455,7 +452,7 @@ include::{section-java-package}/usingstreams/primitives/Streams_Primitives.java[
123
----
-. É possível transformar um _Stream_ comum em um _Stream_ de primitivos utilizando as operações `mapTo*`.
+. You can transform a common _Stream_ into a _Stream_ of primitives using `mapTo*` operations.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_MapTo.java
@@ -463,18 +460,18 @@ include::{section-java-package}/usingstreams/primitives/Streams_Primitives.java[
include::{section-java-package}/usingstreams/primitives/Streams_MapTo.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
- Stream para IntStream
+ Stream to IntStream
1234
- Stream para LongStream
+ Stream to LongStream
1234
- Stream para DoubleStream
+ Stream to DoubleStream
1.02.03.04.0
----
-. É possível gerar Streams infinitos com o método `generate`.
+. You can generate infinite Streams with the `generate` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_Generate.java
@@ -482,23 +479,23 @@ include::{section-java-package}/usingstreams/primitives/Streams_MapTo.java[tag=c
include::{section-java-package}/usingstreams/primitives/Streams_Generate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
- IntStream infinito de números aleatórios
+ infinity IntStream of random numbers
2111846625
-1692075394
122693397
- DoubleStream infinito de números aleatórios
+ infinity DoubleStream of random numbers
0.913037010633669
0.23669861350384735
0.32655918031847697
----
+
-Nesse caso os _Streams_ são realmente infinitos. Só foram apresentados 3 números de cada pois existe a operação `limit`, caso contrário a execução do programa também seria sem fim.
+In this case the _Streams_ are really infinite. Only 3 numbers of each were displayed as there is the `limit` operation, otherwise program execution would also be endless.
-. É possível utilizar a operação `rangeClosed` ao invés de `range`, deixando o código mais legível.
+. You can use the `rangeClosed` operation instead of `range`, making the code more readable.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_RangeClosed.java
@@ -506,16 +503,16 @@ Nesse caso os _Streams_ são realmente infinitos. Só foram apresentados 3 núme
include::{section-java-package}/usingstreams/primitives/Streams_RangeClosed.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
123
1234
----
+
-Perceba que na chamada utilizando `range`, o último número é exclusivo (não faz parte do _Stream_). No `rangeClosed`, tanto o primeiro quanto o último número são inclusivos (fazem parte do _Stream_).
+Note that in the call using `range`, the last number is unique (not part of _Stream_). In `rangeClosed`, both the first and last numbers are inclusive (they are part of _Stream_).
-. É possível gerar várias estatísticas de _Streams_ utilizando a operação `summaryStatistics`.
+. You can generate various _Streams_ statistics using the `summaryStatistics` operation.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_Statistics.java
@@ -523,23 +520,23 @@ Perceba que na chamada utilizando `range`, o último número é exclusivo (não
include::{section-java-package}/usingstreams/primitives/Streams_Statistics.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Quantidade: 10
-Maior: 9
-Menor: 0
-Soma: 45
-Média: 4.5
+Count: 10
+Max: 9
+Min: 0
+Sum: 45
+Average: 4.5
----
-==== _Reduce_ e _Collectors_
+==== _Reduce_ and _Collectors_
===== Reduce
-_Reduce_ é uma das principais operações final que podem ser feitas em um _Stream_. _Reduce_ é uma operação que transforma os vários valores do _Stream_ em um único valor. Várias operações apresentadas anteriormente são um tipo de _Reduce_, como: `max`, `min` e `summaryStatistics`. Porém, nem sempre essas operações são suficientes, e por isso existem os métodos `reduce`. Eles permitem a implementação de operações personalizadas de _Reduce_.
+_Reduce_ is one of the main final operations that can be done on a _Stream_. It is an operation that transforms multiple _Stream_ values into a single value. Several operations previously presented are a type of _Reduce_, such as: `max`, `min` and `summaryStatistics`. However, these operations are not always sufficient, so there are `reduce` methods. They allow the implementation of _Reduce_ custom operations.
-. É possível criar uma operação de Reduce personalizada com o método `reduce()` que recebe 1 argumento.
+. You can create a custom Reduce operation with the `reduce()` method that takes 1 argument.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_Reduce.java
@@ -547,15 +544,15 @@ _Reduce_ é uma das principais operações final que podem ser feitas em um _Str
include::{section-java-package}/usingstreams/reduce/Streams_Reduce.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
336
----
+
-Nesse caso está sendo feito um _Reduce_ onde o resultado da operação anterior é passado para a próxima execução. Ou seja, primeiro é feita a multiplicação de 7 * 2, que é 14. Então a função é chamada novamente passando como argumento o resultado anterior (14) e o próximo número do Stream (3). O resultado é 42. Então a função é chamada uma última vez passando o resultado anterior (42) e o próximo número do Stream (8), o que dá o resultado de 336.
+In this case a _Reduce_ is being made where the result of the previous operation is passed to the next execution. That is, first we multiply 7 * 2, which is 14. Then the function is called again passing as argument the previous result (14) and the next Stream number (3). The result is 42. Then the function is called one last time passing the previous result (42) and the next Stream number (8), which gives the result of 336.
-. É possível criar uma operação de _Reduce_ informando o valor de identidade.
+. You can create a _Reduce_ operation by entering the identity value.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_ReduceIdentity.java
@@ -563,17 +560,17 @@ Nesse caso está sendo feito um _Reduce_ onde o resultado da operação anterior
include::{section-java-package}/usingstreams/reduce/Streams_ReduceIdentity.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
336
----
+
-Nesse caso é possível informar o valor de identidade da função. O conceito de valor ou função de identidade são um pouco mais complexos, mas para a certificação apenas compreenda que ele representa um valor neutro. Ou seja, para a operação de multiplicação, o valor de identidade é 1, pois qualquer valor multiplicado por 1 resulta nele mesmo. Caso fosse uma operação de soma, o valor de identidade seria 0, pois qualquer valor somado a 0 resulta nele mesmo.
+In this case you can enter the identity value of the role. The concept of value or identity function is a bit more complex, but for certification just understand that it represents a neutral value. That is, for the multiplication operation, the identity value is 1, because any value multiplied by 1 results in itself. If it were a sum operation, the identity value would be 0 because any value added to 0 results in itself.
+
-Além disso, se o _Stream_ estiver vazio, o valor de identidade será retornado. Por isso, diferente do exemplo anterior, não é necessário retornar um `Optional`.
+Also, if _Stream_ is empty, the identity value is returned. Therefore, unlike the previous example, it is not necessary to return an `Optional`.
-. É possível criar uma operação de _Reduce_ que pode ser executada em várias _Threads_ e depois combinada em um único valor.
+. You can create a _Reduce_ operation that can be performed on multiple _Threads_ and then combined into a single value.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_ReduceCombiner.java
@@ -581,21 +578,21 @@ Além disso, se o _Stream_ estiver vazio, o valor de identidade será retornado.
include::{section-java-package}/usingstreams/reduce/Streams_ReduceCombiner.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
336
----
+
-Nesse caso é passado um argumento adicional. Ele é a função de combinação. Essa função é utilizada quando o _Stream_ é paralelo, ou seja, utiliza mais de uma _thread_. Ela pega o valor retornado por 2 ou mais _threads_ e combina-os em um único valor. Em uma operação de multiplicação, a combinação também é uma multiplicação. Ou seja, caso a primeira _thread_ multiplique 7 e 2, resultando em 14, e a segunda multiplique 3 e 8, resultando em 24, a função de combinação só precisa multiplicar 14 por 24 para chegar ao valor de 336. Sendo assim, a função de combinação só faz sentido em um _Stream_ paralelo, que será apresentado no próximo capítulo.
+In this case, an additional argument is passed. It is the combination function. This function is used when _Stream_ is parallel, in other words, it uses more than one _thread_. It takes the value returned by 2 or more _threads_ and combines them into a single value. In a multiplication operation, the combination is also a multiplication. That is, if the first _thread_ multiplies 7 and 2, resulting in 14, and the second _thread_ multiplies 3 and 8, resulting in 24, the combination function only needs to multiply 14 by 24 to reach the value of 336. Thus, the function combination only makes sense in a parallel _Stream_, which will be presented in the next chapter.
===== Collect
-A operação final `collect` também é um tipo de _Reduce_, porém é utilizada para objetos mutáveis. Ou seja, ao invés de utilizar a operação `reduce` com `String`, provavelmente seria mais eficiente utilizar a operação `collect` com a classe `StringBuilder`, para evitar a criação de vários objetos do tipo `String`. Como Java utiliza muitos objetos mutáveis, incluindo listas e mapas, geralmente a operação `collect` será mais eficiente do que a `reduce`.
+The `collect` final operation is also a type of _Reduce_ but is used for mutable objects. That is, instead of using the `reduce` operation with `String`, it would probably be more efficient to use the `collect` operation with the `StringBuilder` class to avoid creating multiple `String` objects. Because Java uses many mutable objects, including lists and maps, generally the `collect` operation will be more efficient than `reduce`.
-Por serem muito comuns, existem vários _Collectors_ já implementados no Java, disponíveis na classe `Collectors`.
+Because they are very common, there are several _Collectors_ already implemented in Java, available in the `Collectors` class.
-. É possível utilizar um `Collector` que junta várias `Strings`.
+. It is possible to use a `Collector` that joins several `Strings`.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorJoining.java
@@ -603,13 +600,13 @@ Por serem muito comuns, existem vários _Collectors_ já implementados no Java,
include::{section-java-package}/usingstreams/collect/Streams_CollectorJoining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
----
-. É possível utilizar um `Collector` para representar cada elemento como um número e calcular a média entre eles.
+. You can use a `Collector` to represent each element as a number and average them.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorAveragingInt.java
@@ -617,13 +614,13 @@ ABC
include::{section-java-package}/usingstreams/collect/Streams_CollectorAveragingInt.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
6.2
----
-. É possível utilizar um `Collector` para armazenar os elementos de um _Stream_ em uma nova coleção.
+. You can use a `Collector` to store the elements of a _Stream_ in a new collection.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorToCollect.java
@@ -631,7 +628,7 @@ include::{section-java-package}/usingstreams/collect/Streams_CollectorAveragingI
include::{section-java-package}/usingstreams/collect/Streams_CollectorToCollect.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ArrayList: [1, 2, 3, 4]
@@ -640,7 +637,7 @@ LinkedList: [1, 2, 3, 4]
TreeSet: [1, 2, 3, 4]
----
-. É possível utilizar um `Collector` para armazenar os elementos de um _Stream_ em um mapa.
+. You can use a `Collector` to store the elements of a _Stream_ in a map.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorToMap.java
@@ -648,13 +645,13 @@ TreeSet: [1, 2, 3, 4]
include::{section-java-package}/usingstreams/collect/Streams_CollectorToMap.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{Roseany=7, Amélia=6, Rodrigo=7, Rinaldo=7, Luiz=4}
----
-. Também é possível armazenar em um mapa para casos em que a chave for se repetir. O terceiro argumento do método `toMap` define a regra de mesclagem dos valores para chaves iguais.
+. It is also possible to store in a map in cases where the key will be repeated. The third argument of the `toMap` method defines the rule to merge values to equal keys.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorToMapDuplicateKey.java
@@ -662,13 +659,13 @@ include::{section-java-package}/usingstreams/collect/Streams_CollectorToMap.java
include::{section-java-package}/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=Luiz, 6=Amélia, 7=Rinaldo,Rodrigo,Roseany}
----
-. É possível utilizar um `Collector` que cria um mapa agrupando valores que tem a mesma chave em uma lista.
+. You can use a `Collector` that creates a map by grouping values that have the same key in a list.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorGroupingBy.java
@@ -676,13 +673,13 @@ include::{section-java-package}/usingstreams/collect/Streams_CollectorToMapDupli
include::{section-java-package}/usingstreams/collect/Streams_CollectorGroupingBy.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=[Luiz], 6=[Amélia], 7=[Rinaldo, Rodrigo, Roseany]}
----
-. Também é possível personalizar a maneira que o valores com chaves iguais serão combinados.
+. You can also customize the way that values with equal keys will be combined.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorGroupingByDownstream.java
@@ -690,15 +687,15 @@ include::{section-java-package}/usingstreams/collect/Streams_CollectorGroupingBy
include::{section-java-package}/usingstreams/collect/Streams_CollectorGroupingByDownstream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=Luiz, 6=Amélia, 7=Rinaldo,Rodrigo,Roseany}
----
+
-Perceba que nesse caso os valores foram combinados utilizando outro _Collector_, que agrupou os nomes separando com vírgula.
+Note that in this case the values were combined using another _Collector_, which grouped the names separating with commas.
-. Também é possível definir qual tipo de mapa será utilizado para agrupar.
+. You can also define which type of map will be used for grouping.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorGroupingByMapFactory.java
@@ -706,15 +703,15 @@ Perceba que nesse caso os valores foram combinados utilizando outro _Collector_,
include::{section-java-package}/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=Luiz, 6=Amélia, 7=Rinaldo,Rodrigo,Roseany}
----
+
-Perceba que o resultado desse exemplo é idêntico ao anterior, porém foi passado um argumento a mais, que é o construtor do mapa que deveria ser utilizado.
+Note that the result of this example is identical to the previous one, but one more argument was passed, which is the map constructor that should be used.
-. É possível utilizar um `Collector` que particiona valores em `True` ou `False` a partir de um função do tipo `Predicate`.
+. You can use a `Collector` that partitions values in `True` or `False` from a function of type `Predicate`.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorPartitioningBy.java
@@ -722,15 +719,15 @@ Perceba que o resultado desse exemplo é idêntico ao anterior, porém foi passa
include::{section-java-package}/usingstreams/collect/Streams_CollectorPartitioningBy.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{false=[Luiz, Amélia], true=[Rinaldo, Rodrigo, Roseany]}
----
+
-Perceba que nesse caso a regra de particionamento são os nomes que iniciam-se por `R`.
+Note that in this case the partitioning rule is the names beginning with `R`.
-. Também é possível personalizar como a combinação dos valores particionados será feita.
+. You can also customize how the combination of partitioned values will be done.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorPartitioningByDownstream.java
@@ -738,15 +735,15 @@ Perceba que nesse caso a regra de particionamento são os nomes que iniciam-se p
include::{section-java-package}/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{false=Luiz,Amélia, true=Rinaldo,Rodrigo,Roseany}
----
+
-Perceba que nesse caso os valores foram combinados utilizando um outro `Collector`, que juntou os valores daquela mesma chave em uma única `String` separados por vírgula.
+Note that in this case the values were combined using another `Collector`, which merged the values of that same key into a single `String` separated by commas.
-. É possível adicionar uma camada a mais de transformação ao utilizar um `Collector`, utilizando o método `mapping`.
+. You can add one more layer of transformation using a `Collector` using the `mapping` method.
+
[source,java,indent=0]
.{java-package}/usingstreams/primitives/Streams_CollectorMapping.java
@@ -754,20 +751,20 @@ Perceba que nesse caso os valores foram combinados utilizando um outro `Collecto
include::{section-java-package}/usingstreams/collect/Streams_CollectorMapping.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=LUIZ, 6=AMÉLIA, 7=RINALDO,RODRIGO,ROSEANY}
----
+
-Esse tipo de código, apesar de complexo, pode aparecer no exame de certificação. É recomendado praticar esses exemplos com uma IDE para entender de fato seus comportamentos. Acesse os códigos de exemplo deste livro para facilitar seus estudos.
+This type of code, while complex, may appear on the certification exam. It is recommended to practice these examples with an IDE to really understand their behaviors. Access the sample codes in this book to facilitate your study.
-.Referências
+.References
****
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
@@ -777,4 +774,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html[Interface Stream.] Java Plataform SE 8.
-****
\ No newline at end of file
+****
diff --git a/book/05-java-streams/sections/02-parallel-streams.asc b/book/05-java-streams/sections/02-parallel-streams.asc
index 8ba32af..6d226f8 100644
--- a/book/05-java-streams/sections/02-parallel-streams.asc
+++ b/book/05-java-streams/sections/02-parallel-streams.asc
@@ -1,20 +1,18 @@
:java-package: src/org/j6toj8/streams
:section-java-package: ../../../{java-package}
-=== Streams Paralelos
+=== Parallel Streams
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses parallel streams, including decomposition operation and reduction operation in streams
--
-Desenvolver código que usa Streams Paralelos, incluindo operação de decomposição e operação de redução em Streams
--------------------------------------------------
-_Streams_ podem ser sequenciais ou paralelos. Os sequencias foram vistos na seção anterior, enquanto os paralelos serão apresentados nesta seção. _Streams_ paralelos são executados por mais de uma _Thread_, geralmente uma quantidade igual à quantidade de núcleos do processador onde a aplicação está sendo executada. Apesar disso, nem sempre é útil utilizá-los. Seu ganho real é em _Streams_ com grande volumes de dados. Em um _Stream_ pequeno, transformá-lo em paralelo pode até causar uma perda de performance.
+_Streams_ can be sequential or parallel. Sequential was seen in the previous section, while parallels will be presented in this section. Parallel _Streams_ are executed by more than one _Thread_, usually equal to the number of processor cores where the application is running. Nevertheless, it is not always useful to use them. Your actual gain is _Streams_ using large volumes of data. In a small _Stream_, turning it parallel can even cause a loss of performance.
-Ao utilizar qualquer tipo de _Stream_, é recomendável não executar funções lambdas que causem efeitos colaterais, como mudanças no estado de objetos. Em _Streams_ paralelos essa recomendação é ainda mais importante.
+When using any kind _Stream_, it is recommended not to perform Lambda functions that cause side effects, such as changes in the state of objects. In parallel _Streams_, this recommendation is even more important.
-. É possível transformar qualquer _Stream_ em paralelo utilizando o método `parallel`.
+. You can make any _Stream_ parallel using the `parallel` method.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_Parallel.java
@@ -22,7 +20,7 @@ Ao utilizar qualquer tipo de _Stream_, é recomendável não executar funções
include::{section-java-package}/parallelstreams/Streams_Parallel.java[tag=code]
----
-. É possível criar _Streams_ paralelos diretamente em Coleções através do método `parallelStream`.
+. You can create parallel _Streams_ directly in Collections through the `parallelStream` method.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelStream.java
@@ -30,7 +28,7 @@ include::{section-java-package}/parallelstreams/Streams_Parallel.java[tag=code]
include::{section-java-package}/parallelstreams/Streams_ParallelStream.java[tag=code]
----
-. Ao utilizar a operação `forEach` em um _Stream_ paralelo, a ordem de execução não é garantida.
+. When using the `forEach` operation on a parallel _Stream_, the order of execution is not guaranteed.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelForEach.java
@@ -38,22 +36,22 @@ include::{section-java-package}/parallelstreams/Streams_ParallelStream.java[tag=
include::{section-java-package}/parallelstreams/Streams_ParallelForEach.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Sequencial:
+Sequential:
A
B
C
-Paralelo:
+Parallel:
B
C
A
----
+
-O _Stream_ paralelo poderia ter impresso em qualquer ordem, pois não há nenhuma garantia na ordem em que os elementos serão tratados.
+The parallel _Stream_ could have printed in any order as there is no guarantee in the order in which the elements will be handled.
-. A operação `forEachOrdered` garante que a ordem será mantida mesmo em _Streams_ paralelos.
+. The `forEachOrdered` operation ensures that order will be maintained even in parallel _Streams_.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelForEachOrdered.java
@@ -61,20 +59,20 @@ O _Stream_ paralelo poderia ter impresso em qualquer ordem, pois não há nenhum
include::{section-java-package}/parallelstreams/Streams_ParallelForEachOrdered.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Sequencial:
+Sequential:
A
B
C
-Paralelo:
+Parallel:
A
B
C
----
-. Em coleções com muitos objetos pode haver um ganho considerável de performance.
+. In collections with many objects, there can be a considerable performance gain.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelPerformance.java
@@ -82,16 +80,16 @@ C
include::{section-java-package}/parallelstreams/Streams_ParallelPerformance.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tempo stream sequencial: 9863
-Tempo stream paralelo: 1479
+Sequential Stream time: 9863
+Parallel Stream time: 1479
----
+
-Perceba que na máquina onde o código foi executado, a execução em paralelo demorou apenas 15% do tempo da execução sequencial. Esse não é um teste minucioso, mas mostra o potencial de _Streams_ paralelos.
+Note that on the machine where the code was executed, parallel execution took only 15% of the sequential execution time. This is not a thorough test, but it does show the potential of parallel _Streams_.
-. Operações intermediárias que alteram o estado de objetos podem gerar resultados inesperados ao serem executadas em paralelo.
+. Intermediate operations that change the state of objects can produce unexpected results when executed in parallel.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelStatefulOperation.java
@@ -99,22 +97,22 @@ Perceba que na máquina onde o código foi executado, a execução em paralelo d
include::{section-java-package}/parallelstreams/Streams_ParallelStatefulOperation.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Ordem no forEachOrdered:
+Order on forEachOrdered:
A
B
C
-Ordem na synchronizedList:
+Order on synchronizedList:
A
C
B
----
+
-Perceba que a ordem foi respeitada na última operação do _Stream_, o `forEachOrdered`, mas não foi respeitada na execução da operação intermediária `map`. Isso ocorre porque essa operação intermediária não precisa seguir a ordem dos itens do stream.
+Note that the order was respected in the last _Stream_ operation, `forEachOrdered`, but was not respected when performing the `map` intermediate operation. This is because this intermediate operation does not have to follow the order of stream items.
-. Diferente da execução em um _Stream_ sequencial, a operação `findAny` traz resultados realmente aleatórios ao ser executada em um _Stream_ paralelo.
+. Unlike running in a sequential _Stream_, the `findAny` operation brings really random results when executed in a parallel _Stream_.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelFindAny.java
@@ -122,14 +120,14 @@ Perceba que a ordem foi respeitada na última operação do _Stream_, o `forEach
include::{section-java-package}/parallelstreams/Streams_ParallelFindAny.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-findAny Sequencial: 7
-findAny Paralelo: 9
+findAny Sequential: 7
+findAny Parallel: 9
----
-. Ao realizar uma operação de reduce não há problema caso o acumulador seja associativo.
+. When performing a reduce operation there is no problem if the accumulator is associative.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelReduceAssociative.java
@@ -137,16 +135,16 @@ findAny Paralelo: 9
include::{section-java-package}/parallelstreams/Streams_ParallelReduceAssociative.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
13440
13440
----
+
-Perceba que o resultado com o Stream sequencial é idêntico ao paralelo. Isso ocorre porque a operação de multiplicação é associativa, ou seja, fazer `(2 x 2) x (3 x 3)` é o mesmo que fazer `(2 x 2 x 3) x 3`, ou até mesmo `2 x (2 x 3) x 3`.
+Note that the result with sequential Stream is identical to parallel. This is because the multiplication operation is associative, i.e., doing `(2 x 2) x (3 x 3)` is the same as doing `(2 x 2 x 3) x 3`, or even `2 x (2x3) x3`.
-. Ao realizar uma operação de reduce acumuladores não-associativos irá gerar resultados inesperados.
+. Performing a reduce non-associative accumulator operation will produce unexpected results.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelReduceNonAssociative.java
@@ -154,16 +152,16 @@ Perceba que o resultado com o Stream sequencial é idêntico ao paralelo. Isso o
include::{section-java-package}/parallelstreams/Streams_ParallelReduceNonAssociative.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-18
8
----
+
-Isso ocorre pois a operação de subtração não é associativa, então o resultado pode variar conforme o _Stream_ for "fatiado" para ser executado em paralelo. Ou seja, fazer `1 - 2 - 3 - 4` não é o mesmo que fazer `(1 - 2) - (3 - 4)`.
+This is because the subtraction operation is not associative, so the result may vary as _Stream_ is "sliced" to run in parallel. That is, doing `1 - 2 - 3 - 4` is not the same as doing `(1 - 2) - (3 - 4)`.
-. Para coletar o resultado de um _Stream_ paralelo em um mapa, utilize a operação `toConcurrentMap`.
+. To collect the result of a parallel _Stream_ on a map, use the `toConcurrentMap` operation.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelToConcurrentMap.java
@@ -171,16 +169,16 @@ Isso ocorre pois a operação de subtração não é associativa, então o resul
include::{section-java-package}/parallelstreams/Streams_ParallelToConcurrentMap.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
toMap: {Roseany=7, Amélia=6, Rodrigo=7, Rinaldo=7, Luiz=4}
toConcurrentMap: {Amélia=6, Roseany=7, Rodrigo=7, Rinaldo=7, Luiz=4}
----
+
-Perceba que o resultados das operações pode ser diferente. Ao utilizar o _Collector_ `toConcurrentMap` em um _Stream_ paralelo, as operações podem ser executadas em qualquer ordem e não há necessidade de criar múltiplos `Map's` para serem combinados posteriormente. Em grandes _Streams_, isso pode ocasionar em um ganho de performance.
+Note that the results of operations may differ. By using _Collector_ `toConcurrentMap` in a parallel _Stream_, operations can be performed in any order and there is no need to create multiple `Map's` to be combined later. In large _Streams_, this can lead to a performance gain.
-. Para coletar o resultado de um Stream paralelo utilize _groupingByConcurrent_ ao invés de _groupingBy_.
+. To collect the result of a parallel stream use _groupingByConcurrent_ instead of _groupingBy_.
+
[source,java,indent=0]
.{java-package}/parallelstreams/Streams_ParallelGroupingByConcurrent.java
@@ -188,21 +186,21 @@ Perceba que o resultados das operações pode ser diferente. Ao utilizar o _Coll
include::{section-java-package}/parallelstreams/Streams_ParallelGroupingByConcurrent.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
{4=[Luiz], 6=[Amélia], 7=[Rinaldo, Rodrigo, Roseany]}
{4=[Luiz], 6=[Amélia], 7=[Roseany, Rodrigo, Rinaldo]}
----
+
-Pelo mesmo motivo do exemplo anterior, a ordem pode variar ao utilizar o `groupingByConcurrent`, porém pode haver ganho de performance em grandes _Streams_ paralelos, pois a ordem não é necessariamente seguida e não há necessidade de criar múltiplos mapas.
+For the same reason as in the previous example, the order may vary when using `groupingByConcurrent`, but there may be performance gains on large parallel _Streams_ as the order is not necessarily followed and there is no need to create multiple maps.
-.Referências
+.References
****
* Working with Parallel Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 366). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 366). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
@@ -212,4 +210,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html[Interface Stream.] Java Plataform SE 8.
-****
\ No newline at end of file
+****
diff --git a/book/06-concurrency/sections/01-concurrent-package.asc b/book/06-concurrency/sections/01-concurrent-package.asc
index 8a14150..df3d058 100644
--- a/book/06-concurrency/sections/01-concurrent-package.asc
+++ b/book/06-concurrency/sections/01-concurrent-package.asc
@@ -1,22 +1,20 @@
:java-package: src/org/j6toj8/concurrency
:section-java-package: ../../../{java-package}
-=== Pacote `Concurrent`
+=== Concurrent package
-.Objetivo
+.Objective
--------------------------------------------------
Use classes from the java.util.concurrent package including CyclicBarrier and CopyOnWriteArrayList with a focus on the advantages over and differences from the traditional java.util collections
--
-Usar classes do pacote java.util.concurrent, incluindo CyclicBarrier e CopyOnWriteArrayList, com foco nas vantagens e diferenças das Coleções tradicionais do pacote java.util
--------------------------------------------------
-O pacote `java.util.concurrent` inclui inúmeras classes para serem utilizadas em aplicações multi-thread. Nesta seção serão apresentadas algumas dessas classes.
+The `java.util.concurrent` package includes numerous classes for use in multi-threaded applications. In this section, some of these classes will be presented.
-Muitas das classes do pacote concurrent são apenas versões das coleções comuns, porém com blocos __syncronized__, garantindo que múltiplas _threads_ poderão acessá-las ao mesmo tempo mantendo sua integridade. As classes __ConcurrentHashMap__, _ConcurrentLinkedQueue_ e _ConcurrentLinkedDeque_ são exemplos disso. Por isso é importante conhecer e lembrar das coleções comuns do Java 6.
+Many of the concurrent package classes are just versions of the common collections, but with _synchronized_ blocks, ensuring that multiple _threads_ can access them while maintaining their integrity. The _ConcurrentHashMap_, _ConcurrentLinkedQueue_, and _ConcurrentLinkedDeque_ classes are examples of this. That's why it's important to know and remember the common Java 6 collections.
-Todas as seções deste capítulo podem conter exemplos maiores do que os que foram apresentados até agora, principalmente quando for necessário a criação de mútiplas __Threads__. É importante dedicar um tempo maior para entender cada um desses exemplos.
+All sections of this chapter may contain larger examples than presented so far, especially when creating multiple _Threads_ is required. It is important to spend more time understanding each of these examples.
-. É possível criar uma *Fila* que lança uma exceção após um tempo predefinido utilizando a classe ``LinkedBlockingQueue``.
+. You can create a *Queue* that throws an exception after a predefined time using the `LinkedBlockingQueue` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java
@@ -24,7 +22,7 @@ Todas as seções deste capítulo podem conter exemplos maiores do que os que fo
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java[tag=code]
----
-. É possível criar uma *Fila Duplamente Ligada (Deque)* que lança uma exceção após um tempo predefinido utilizando a classe ``LinkedBlockingDeque``.
+. You can create a *Double Queue (Deque)* that throws an exception after a preset time using the `LinkedBlockingDeque` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java
@@ -32,7 +30,7 @@ include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingQueu
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java[tag=code]
----
-. É possível criar uma lista que aloca todo o seu conteúdo em um novo _array_ sempre que é modificada utilizando a classe ``CopyOnWriteArrayList``.
+. You can create a list that allocates all of its contents to a new _array_ whenever it is modified using the `CopyOnWriteArrayList` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java
@@ -40,20 +38,20 @@ include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingDequ
include::{section-java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
A
B
C
-Lista final: [A, B, C, D]
+Final list: [A, B, C, D]
----
+
-Perceba que foi possível acrescentar um valor na lista durante a execução do _forEach_. Em uma lista tradicional haveria ocorrido uma ``ConcurrentModificationException``.
+Note that it was possible to add a value to the list during _forEach_ execution. In a traditional list there would have been a `ConcurrentModificationException`.
+
-Perceba também que, mesmo alterando a lista dentro do __forEach__, a letra "D" não aparece no console. Isso ocorre pois, quando a letra "D" foi inserida na lista, um novo _array_ foi alocado internamente contendo todos os novos elementos, e a iteração continuou ocorrendo no _array_ antigo.
+Also note that even if you change the list within _forEach_, the letter "D" does not appear on the console. This is because when the letter "D" was entered in the list, a new _array_ was internally allocated containing all the new elements, and the iteration continued to occur in the old _array_.
-. É possível criar versões _syncronized_ de coleções utilizando métodos utilitários da classe ``Collections``.
+. You can create _synchronized_ versions of collections using utility methods of the `Collections` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java
@@ -61,7 +59,7 @@ Perceba também que, mesmo alterando a lista dentro do __forEach__, a letra "D"
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java[tag=code]
----
-. *Não* é possível adicionar ou remover elementos durante o _forEach_ de uma coleção sincronizada que foi criada utilizando o método da classe ``Collections``.
+. *Cannot* add or remove elements during _forEach_ from a synchronized collection that was created using the `Collections` class method.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java
@@ -69,7 +67,7 @@ include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncron
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Exception in thread "main" java.util.ConcurrentModificationException
@@ -79,9 +77,9 @@ Exception in thread "main" java.util.ConcurrentModificationException
at org.j6toj8.concurrency.concurrentpackage.Concurrency_CollectionsSyncronizedForEach.main(Concurrency_CollectionsSyncronizedForEach.java:18)
----
+
-Perceba que, apesar do `Map` ter sido transformado em __syncronized__, não é possível alterá-lo durante uma iteração com __forEach__. Isso é possível apenas nas versões _Concurrent_ das coleções.
+Note that although `Map` has been turned into _synchronized_, it cannot be changed during an iteration with _forEach_. This is only possible in _Concurrent_ versions of collections.
-. É possível sincronizar a execução de várias _threads_ utilizando a classe ``CyclicBarrier``.
+. You can synchronize the execution of multiple _threads_ using the `CyclicBarrier` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CyclicBarrier.java
@@ -89,42 +87,42 @@ Perceba que, apesar do `Map` ter sido transformado em __syncronized__, não é p
include::{section-java-package}/concurrentpackage/Concurrency_CyclicBarrier.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread-2: Primeira Parte
-Thread-1: Primeira Parte
-Thread-0: Primeira Parte
-Thread-1: Segunda Parte
-Thread-2: Segunda Parte
-Thread-0: Segunda Parte
-Thread-0: Terceira Parte
-Thread-1: Terceira Parte
-Thread-2: Terceira Parte
+Thread-2: First Part
+Thread-1: First Part
+Thread-0: First Part
+Thread-1: Second Part
+Thread-2: Second Part
+Thread-0: Second Part
+Thread-0: Third Part
+Thread-1: Third Part
+Thread-2: Third Part
----
+
-Neste exemplo estão sendo criadas 3 __threads__. Todas executam instâncias da classe `Acao` que recebem a mesma instância da classe ``CyclicBarrier``. Toda vez que uma _thread_ faz uma chamada ao método `await` da instância de ``cyclicBarrier``, ela fica suspensa até que todas as outras _threads_ cheguem até aquele mesmo ponto. Por isso todas as _threads_ imprimem no console de forma sincronizada. Se não houvesse sincronização, a saída no console seria completamente imprevisível. Abaixo é o exemplo de uma execução sem a chamada ao método `await`:
+In this example 3 _threads_ are being created. All run instances of the `Action` class that receive the same instance of the `CyclicBarrier` class. Every time a _thread_ calls the `await` method of the `cyclicBarrier` instance, it is suspended until all other _threads_ reach that same point. That's why all _threads_ print to the console synchronously. If there was no synchronization, the console output would be completely unpredictable. Below is an example of an execution without calling the `await` method:
+
-.Saída no console caso não houvesse CyclicBarrier
+.console output if there was no CyclicBarrier
[source,console]
----
-Thread-0: Primeira Parte
-Thread-1: Primeira Parte
-Thread-1: Segunda Parte
-Thread-1: Terceira Parte
-Thread-2: Primeira Parte
-Thread-0: Segunda Parte
-Thread-2: Segunda Parte
-Thread-0: Terceira Parte
-Thread-2: Terceira Parte
-
+Thread-0: First Part
+Thread-1: First Part
+Thread-1: Second Part
+Thread-1: Third Part
+Thread-2: First Part
+Thread-0: Second Part
+Thread-2: Second Part
+Thread-0: Third Part
+Thread-2: Third Part
----
+.References
****
* Using Concurrent Collections
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Kindle Edition.
* https://www.baeldung.com/java-util-concurrent[Overview of the java.util.concurrent.]
@@ -134,4 +132,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html[Package java.util.concurrent.] Java Plataform SE 8.
-****
\ No newline at end of file
+****
diff --git a/book/06-concurrency/sections/02-locks.asc b/book/06-concurrency/sections/02-locks.asc
index c2d0439..8d652b8 100644
--- a/book/06-concurrency/sections/02-locks.asc
+++ b/book/06-concurrency/sections/02-locks.asc
@@ -3,20 +3,18 @@
=== Locks
-.Objetivo
+.Objective
--------------------------------------------------
Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks and java.util.concurrent.atomic packages to support lock-free thread-safe programming on single variables
--
-Usar classes dos tipos Lock, ReadWriteLock, e ReentrantLock dos pacotes java.util.concurrent.locks e java.util.concurrent.atomic para suportar programação sem bloqueio e multi-thread em variáveis únicas
--------------------------------------------------
-As classes e interfaces `Lock`, `ReadWriteLock` e `ReentrantLock` permitem obter diferentes tipos de _Locks_ (em tradução livre: bloqueios ou travas). Esses _Locks_ são utilizados para que um número limitado de _threads_ tenham acesso a mesma variável em um determinado momento, ou para que apenas uma delas possa alterar seu valor.
+The `Lock`, `ReadWriteLock` and `ReentrantLock` classes and interfaces allow for different types of _Locks_. These _Locks_ are used so that a limited number of _threads_ have access to the same variable at any given time, or so that only one of them can change its value.
-Nesta seção serão apresentados exemplos utilizando essas classes e interfaces. Assim como em outras seções deste capítulo, os exemplos podem ser grandes quando for necessário a criação de __threads__. Dedique um tempo maior para entendê-los completamente.
+In this section examples will be presented using these classes and interfaces. As in other sections of this chapter, examples can be large when creating _threads_ is required. Take more time to fully understand them.
==== Reentrant Lock
-. É possível adquirir um _Lock_ utilizando a classe ``ReentrantLock``.
+. You can get a _Lock_ using the `ReentrantLock` class.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReentrantLock.java
@@ -24,15 +22,15 @@ Nesta seção serão apresentados exemplos utilizando essas classes e interfaces
include::{section-java-package}/locks/Locks_ReentrantLock.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
----
+
-Perceba que o _lock_ é removido dentro de um bloco ``finally``. Isso garante que uma _thread_ não irá ficar com um _lock_ indeterminadamente.
+Note that _lock_ is removed within a `finally` block. This ensures that a _thread_ will not have an _lock_ indefinitely.
-. Chamar o método unlock sem ter obtido um lock anteriormente irá lançar uma exceção.
+. Calling the unlock method without previously locking will throw an exception.
+
[source,java,indent=0]
.{java-package}/locks/Locks_UnlockWithoutLock.java
@@ -40,7 +38,7 @@ Perceba que o _lock_ é removido dentro de um bloco ``finally``. Isso garante qu
include::{section-java-package}/locks/Locks_UnlockWithoutLock.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
@@ -51,7 +49,7 @@ Exception in thread "main" java.lang.IllegalMonitorStateException
at org.j6toj8.concurrency.locks.Locks_UnlockWithoutLock.main(Locks_UnlockWithoutLock.java:14)
----
-. É possível tentar obter um _lock_ imediatamente utilizando o método ``tryLock``.
+. You can try to get a _lock_ immediately using the `tryLock` method.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLock.java
@@ -59,13 +57,13 @@ Exception in thread "main" java.lang.IllegalMonitorStateException
include::{section-java-package}/locks/Locks_TryLock.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
----
-. Também é possível tentar obter um _lock_ definindo um tempo de espera máximo.
+. You can also try to get a _lock_ by setting a maximum wait time.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLockTimeout.java
@@ -73,13 +71,13 @@ ABC
include::{section-java-package}/locks/Locks_TryLockTimeout.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
----
-. Em um cenário com várias __threads__, é possível que apenas uma delas consiga obter um __lock__.
+. In a scenario with multiple _threads_, only one of them may be able to obtain a _lock_.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLockMultithread.java
@@ -87,16 +85,16 @@ ABC
include::{section-java-package}/locks/Locks_TryLockMultithread.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread-0: Conseguiu o Lock
-Thread-2: Conseguiu o Lock
+Thread-0: Got the Lock
+Thread-2: Got the Lock
----
+
-Nesta execução com 3 __threads__, apenas duas conseguiram obter o _lock_ imediatamente e imprimir no console. Porém o resultado é imprevisível. Podem existir execuções onde todas obterão o __lock__, e outras em que apenas uma thread conseguirá.
+In this 3 _threads_ run, only two were able to get _lock_ immediately and print to the console. But the result is unpredictable. There may be executions where all will get the _lock_, and others where only one thread will succeed.
-. Uma _thread_ pode obter mais de um _lock_ no mesmo objeto ``Lock``, mas deve desfazer o _lock_ múltiplas vezes também.
+. A _thread_ can get more than one _lock_ on the same `Lock` object, but must undo _lock_ multiple times as well.
+
[source,java,indent=0]
.{java-package}/locks/Locks_LockTwice.java
@@ -104,15 +102,15 @@ Nesta execução com 3 __threads__, apenas duas conseguiram obter o _lock_ imedi
include::{section-java-package}/locks/Locks_LockTwice.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ABC
----
+
-Como a _thread_ chamou `lock` duas vezes, caso ela não houvesse chamado `unlock` duas vezes, outra _thread_ não seria capaz de obter o __lock__.
+Since the _thread_ called the `lock` twice, if it had not called `unlock` twice, another _thread_ would not be able to get the _lock_.
-. É possível garantir uma distribuição mais "justa" de _locks_ passando `true` como argumento para o ``ReentrantLock``.
+. You can ensure a more "fair" distribution of _locks_ by passing `true` as an argument to `ReentrantLock`.
+
[source,java,indent=0]
.{java-package}/locks/Locks_Fair.java
@@ -120,11 +118,11 @@ Como a _thread_ chamou `lock` duas vezes, caso ela não houvesse chamado `unlock
include::{section-java-package}/locks/Locks_Fair.java[tag=code]
----
+
-Ao passar o argumento ``true``, quando várias _threads_ estiverem esperando pelo mesmo __lock__, ele será dado àquela _thread_ que está aguardando a mais tempo.
+When passing the `true` argument, when multiple _threads_ are waiting for the same _lock_, it will be given to that _thread_ that has been waiting the longest.
==== ReentrantReadWriteLock
-. É possível separar _locks_ de leitura e escrita utilizando a classe ``ReadWriteLock``. _Locks_ de leitura podem ser obtidos por múltiplas _threads_, porém _locks_ de escrita não.
+. You can separate read and write _locks_ using the `ReadWriteLock` class. Read _Locks_ can be obtained by multiple _threads_, but write _locks_ cannot.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReadWriteLock.java
@@ -132,18 +130,18 @@ Ao passar o argumento ``true``, quando várias _threads_ estiverem esperando pel
include::{section-java-package}/locks/Locks_ReadWriteLock.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread-0: Conseguiu o Lock de leitura
-Thread-2: Conseguiu o Lock de leitura
-Thread-1: Conseguiu o Lock de leitura
-Thread-1: Conseguiu o Lock de escrita
+Thread-0: Got the read Lock
+Thread-2: Got the read Lock
+Thread-1: Got the read Lock
+Thread-1: Got the write Lock
----
+
-Perceba que todas as _threads_ conseguiram obter o _lock_ de leitura, porém apenas uma conseguiu obter o _lock_ de escrita.
+Note that all _threads_ were able to get read _lock_, but only one could get write _lock_.
-. Se uma _thread_ já possuir o _lock_ de escrita, outras não conseguirão obter nem mesmo o _lock_ de leitura.
+. If one _thread_ already has write _lock_, others will not be able to get even read _lock_.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReadWriteLockInverted.java
@@ -151,23 +149,24 @@ Perceba que todas as _threads_ conseguiram obter o _lock_ de leitura, porém ape
include::{section-java-package}/locks/Locks_ReadWriteLockInverted.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread-0: Conseguiu o Lock de escrita
-Thread-0: Conseguiu o Lock de leitura
+Thread-0: Got the write Lock
+Thread-0: Got the read Lock
----
+
-Perceba que neste exemplo o _lock_ de escrita está sendo obtido *antes* do de leitura, de tal forma que apenas a primeira _thread_ que foi executada conseguiu obter os dois __locks__.
+Note that in this example the write _lock_ is being obtained *before* read, so that only the first _thread_ that was executed was able to get both _locks_.
+.References
****
* Applying Locks
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Kindle Edition.
* https://www.baeldung.com/java-concurrent-locks[Guide to java.util.concurrent.Locks.]
* https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/package-summary.html[Package java.util.concurrent.locks.] Java Plataform SE 8.
-****
\ No newline at end of file
+****
diff --git a/book/06-concurrency/sections/03-execute-tasks.asc b/book/06-concurrency/sections/03-execute-tasks.asc
index cafae44..5ee1a4a 100644
--- a/book/06-concurrency/sections/03-execute-tasks.asc
+++ b/book/06-concurrency/sections/03-execute-tasks.asc
@@ -1,18 +1,16 @@
:java-package: src/org/j6toj8/concurrency
:section-java-package: ../../../{java-package}
-=== Executando tarefas com ExecutorService
+=== Execute tasks with ExecutorService
-.Objetivo
+.Objective
--------------------------------------------------
Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools
--
-Usar Executor, ExecutorService, Executors, Callable, e Future para executar tarefas usando um conjunto de threads
--------------------------------------------------
-A classe `ExecutorService` é utilizada para a criação e execução de __threads__. Geralmente é utilizado um conjunto, ou repositório, de __threads__. A classe `Executors` contém métodos utilitários para a criação desses executores. Serão apresentados os principais usos de ``ExecutorService``.
+The `ExecutorService` class is used for creating and executing _threads_. Usually a set or repository of _threads_ is used. The `Executors` class contains utility methods for creating these executors. The main uses of `ExecutorService` will be presented.
-. É possível executar uma tarefa em uma _thread_ separada utilizando o método ``newSingleThreadExecutor``.
+. You can execute a task in a separate _thread_ using the `newSingleThreadExecutor` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThread.java
@@ -20,22 +18,22 @@ A classe `ExecutorService` é utilizada para a criação e execução de __threa
include::{section-java-package}/executetasks/Tasks_SingleThread.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread Principal: main
-Thread do Executor: pool-1-thread-1
+Main Thread: main
+Executor Thread: pool-1-thread-1
----
+
-O método execute recebe uma instância de ``Runnable``, que nestes exemplos serão criadas na forma de uma expressão lambda.
+The execute method receives an instance of `Runnable`, which in these examples will be created as a lambda expression.
+
-Perceba que a _thread_ utilizada pelo executor é diferente da _thread_ principal.
+Note that the _thread_ used by the performer is different from the main _thread_.
+
-Perceba também que é boa prática chamar o método `shutdown` dentro de um bloco `finally`, buscando não deixar _threads_ pendentes. Fique atento, pois chamar o método `shutdown` *não* garante que a _threads_ foram finalizadas.
+Also note that it is good practice to call the `shutdown` method inside a `finally` block, trying not to leave _threads_ pending. Be aware that calling the `shutdown` *method does not* guarantee that _threads_ has been terminated.
+
-Em um programa real, talvez você não queira que a tarefa seja finalizada logo após a sua criação, como nos exemplos aqui apresentados. Logo, pode ser necessário invocar o `shutdown` em algum ponto do sistema, ou quando a aplicação for encerrada. Apenas lembre-se de invocar o método `shutdown` para que sua aplicação possa ser encerrada corretamente, caso contrário o processo poderá ficar travado impedindo que o programe encerre corretamente..
+In a real application, you may not want the task to be completed soon after its creation, as in the examples presented here. Therefore, it may be necessary to invoke `shutdown` somewhere in the system, or when the application terminates. Just remember to invoke the `shutdown` method so that your application can terminate properly, otherwise the process might get stuck preventing the program from terminating properly.
-. É possível executar várias tarefas em uma mesma _thread_ separada utilizando o mesmo método ``newSingleThreadExecutor``.
+. You can perform multiple tasks on the same separate _thread_ using the same `newSingleThreadExecutor` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadManyTasks.java
@@ -43,18 +41,18 @@ Em um programa real, talvez você não queira que a tarefa seja finalizada logo
include::{section-java-package}/executetasks/Tasks_SingleThreadManyTasks.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa 1 - Thread do Executor: pool-1-thread-1
-Tarefa 2 - Thread do Executor: pool-1-thread-1
-Thread Principal: main
-Tarefa 3 - Thread do Executor: pool-1-thread-1
+Task 1 - Executor Thread: pool-1-thread-1
+Task 2 - Executor Thread: pool-1-thread-1
+Main Thread: main
+Task 3 - Executor Thread: pool-1-thread-1
----
+
-Perceba que todas as tarefas foram executadas pela mesma __thread__, que é diferente e paralela à _thread_ principal.
+Note that all tasks were performed by the same _thread_, which is different and parallel to the main _thread_.
-. É possível chamar `shutdownNow` para *tentar* encerrar todas as _threads_ imediatamente.
+. You can call `shutdownNow` to *try* to terminate all _threads_ immediately.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_ShutdownNow.java
@@ -62,14 +60,14 @@ Perceba que todas as tarefas foram executadas pela mesma __thread__, que é dife
include::{section-java-package}/executetasks/Tasks_ShutdownNow.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Thread Principal: main
-Thread do Executor: pool-1-thread-1
+Main Thread: main
+Executor Thread: pool-1-thread-1
----
-. É possível utilizar o método `submit` para ter informações sobre a tarefa que está sendo executada.
+. You can use the `submit` method to get information about the task being performed.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadSubmit.java
@@ -77,23 +75,23 @@ Thread do Executor: pool-1-thread-1
include::{section-java-package}/executetasks/Tasks_SingleThreadSubmit.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa já finalizada? false
-Thread do Executor: pool-1-thread-1
-Tarefa já finalizada? false
-Tarefa já finalizada? true
-Tarefa já finalizada? true
+Task already completed? false
+Executor Thread: pool-1-thread-1
+Task already completed? false
+Task already completed? true
+Task already completed? true
----
+
-A instância de `Future` representa um valor que será retornado no futuro. Nesse caso é um valor que representa a própria tarefa submetida.
+The instance of `Future` represents a value that will be returned in the future. In this case it is a value that represents the submitted task itself.
+
-Veja que a tarefa inicialmente ainda não havia sido finalizada, mas nas duas últimas impressões no console já havia sido.
+Note that the task initially had not yet been completed, but in the last two impressions on the console had already been.
+
-O resultado desse exemplo irá ser diferente para cada execução, tendo em vista a utilização de mais de uma _thread_: a principal e uma paralela.
+The result of this example will be different for each execution, as it uses more than one _thread_: the main one and a parallel one.
-. Também é possível ver outras informações sobre a tarefa ou tentar cancelar sua execução.
+. You can also view other information about the task or try to cancel its execution.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadFuture.java
@@ -101,21 +99,21 @@ O resultado desse exemplo irá ser diferente para cada execução, tendo em vist
include::{section-java-package}/executetasks/Tasks_SingleThreadFuture.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa já finalizada? false
-Tentando cancelar a tarefa. Conseguiu? true
-Tarefa executando
-Tarefa foi cancelada? true
+Task already completed? false
+Trying to cancel the task. Got it? true
+Task running
+Task was canceled? true
----
+
-Perceba como foi possível cancelar a tarefa mesmo após ela já ter impresso no console.
+Note how you could cancel the job even after it has already printed to the console.
+
-O resultado desse exemplo também será diferente para cada execução.
+The result of this example will also differ for each execution.
-. É possível retornar um valor da tarefa utilizando o método `submit` que recebe uma instância de `Callable`.
+. You can return a task value using the `submit` method that receives an instance of `Callable`.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadCallable.java
@@ -123,17 +121,17 @@ O resultado desse exemplo também será diferente para cada execução.
include::{section-java-package}/executetasks/Tasks_SingleThreadCallable.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Retorno da tarefa: String que será retornada
+Task Return: String to be returned
----
+
-Nesse caso a instância de `Future` representa o valor retornado pela tarefa, uma ``String``.
+In this case the instance of `Future` represents the value returned by the task, a `String`.
+
-É necessário o bloco `catch` para capturar as exeções que podem ser lançadas pelo método `get` da classe `Future`.
+The `catch` block is required to catch the exceptions that can be thrown by the `get` method of the `Future` class.
-. É possível passar uma lista de tarefas para serem executadas utilizando o método ``invokeAll``.
+. You can pass a list of tasks to perform using the `invokeAll` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadInvokeAll.java
@@ -141,15 +139,15 @@ Nesse caso a instância de `Future` representa o valor retornado pela tarefa, um
include::{section-java-package}/executetasks/Tasks_SingleThreadInvokeAll.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Retorno da tarefa: Tarefa 1 executando na thread pool-1-thread-1
-Retorno da tarefa: Tarefa 2 executando na thread pool-1-thread-1
-Retorno da tarefa: Tarefa 3 executando na thread pool-1-thread-1
+Task Return: Task 1 Running on Thread pool-1-thread-1
+Task Return: Task 2 Running on Thread pool-1-thread-1
+Task Return: Task 3 Running on Thread pool-1-thread-1
----
-. É possível passar uma lista de tarefas onde apenas uma será concluída utilizando o método `invokeAny`.
+. It is possible to pass a task list where only one will be completed using the `invokeAny` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadInvokeAny.java
@@ -157,17 +155,17 @@ Retorno da tarefa: Tarefa 3 executando na thread pool-1-thread-1
include::{section-java-package}/executetasks/Tasks_SingleThreadInvokeAny.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Retorno da tarefa: Tarefa 1 executada na thread pool-1-thread-1
+Task Return: Task 1 Running on Thread pool-1-thread-1
----
+
-As outras tarefas são interrompidas ou, como neste caso só temos uma __thread__, nem são executadas.
+The other tasks are interrupted or, as in this case, we only have one _thread_, nor are they executed.
+
-Em um exemplo com inúmeras __threads__, é possível que qualquer uma das 3 tarefas finalize primeiro e interrompa as outras duas.
+In an example with numerous _threads_, it is possible for either of the 3 tasks to finish first and stop the other two.
-. `Runnable` não possui retorno nem pode lançar exceção checada, enquanto `Callable` possui retorno e pode lançar execeção checada. É importante saber diferenciar qual versão do método `submit` está sendo chamado.
+. `Runnable` has no return and cannot throw checked exception, while `Callable` has returned and can throw checked exception. It is essential to know how to differentiate which version of the `submit` method is being called.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_RunnableCallable.java
@@ -175,9 +173,9 @@ Em um exemplo com inúmeras __threads__, é possível que qualquer uma das 3 tar
include::{section-java-package}/executetasks/Tasks_RunnableCallable.java[tag=code]
----
+
-Lembre-se que `Thread.sleep()` lança uma exceção checada.
+Remember that `Thread.sleep()` throws a checked exception.
-. É possível esperar as tarefas finalizarem sua execução por um tempo específico com o método `awaitTermination`.
+. You can expect tasks to finish executing for a specific time with the `awaitTermination` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Tasks_SingleThreadAwaitTermination.java
@@ -185,21 +183,21 @@ Lembre-se que `Thread.sleep()` lança uma exceção checada.
include::{section-java-package}/executetasks/Tasks_SingleThreadAwaitTermination.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa 1 - Thread do Executor: pool-1-thread-1
-Tarefa 2 - Thread do Executor: pool-1-thread-1
-Tarefas finalizadas? false
-Tarefa 3 - Thread do Executor: pool-1-thread-1
-Tarefas finalizadas? true
+Task 1 - Executor Thread: pool-1-thread-1
+Task 2 - Executor Thread: pool-1-thread-1
+Tasks completed? false
+Task 3 - Executor Thread: pool-1-thread-1
+Tasks completed? true
----
+
-Caso as tarefas não tenham terminado depois de 1 segundo, a execução teria continuado normalmente. Não há exceção neste caso. A única diferença seria a saída no console, pois nas duas vezes seria impresso `false`.
+If tasks did not finish after 1 second, execution would have continued normally. There is no exception in this case. The only difference would be the console output, as both times would print `false`.
-==== Tarefas agendadas
+==== Scheduled Tasks
-. É possível agendar tarefas com as classes de `ScheduledExecutorService`.
+. You can schedule tasks with the `ScheduledExecutorService` classes.
+
[source,java,indent=0]
.{java-package}/executetasks/Schedule_SingleThread.java
@@ -207,20 +205,20 @@ Caso as tarefas não tenham terminado depois de 1 segundo, a execução teria co
include::{section-java-package}/executetasks/Schedule_SingleThread.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Agora: 16:05:25.978
-Execução: 16:05:28.984
+Now: 16:05:25.978
+Execution: 16:05:28.984
----
+
-Perceba que a tarefa foi executada aproximadamente 3 segundos após o agendamento.
+Note that the task ran approximately 3 seconds after scheduling.
+
-O método schedule utilizado neste exemplo recebe um _Runnable_, por isso não há retorno na expressão lambda.
+The schedule method used in this example is given a _Runnable_, so there is no return in the lambda expression.
+
-Ao agendar uma tarefa, o programa só encerra após a execução, cancelamento ou interrupção da tarefa.
+When scheduling a task, the program ends only after the task has been executed, canceled or interrupted.
-. É possível agendar uma tarefa com retorno passando uma instância de `Callable`.
+. You can schedule a return task by passing an instance of `Callable`.
+
[source,java,indent=0]
.{java-package}/executetasks/Schedule_SingleThreadCallable.java
@@ -228,16 +226,16 @@ Ao agendar uma tarefa, o programa só encerra após a execução, cancelamento o
include::{section-java-package}/executetasks/Schedule_SingleThreadCallable.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Antes do agendamento: 16:10:48.898
-Depois do agendamento: 16:10:48.903
-Execução: 16:10:51.904
-Depois da execução: 16:10:51.904
+Before Scheduling: 16:10:48.898
+After Scheduling: 16:10:48.903
+Execution: 16:10:51.904
+After execution: 16:10:51.904
----
-. É possível agendar uma tarefa para ser executada a cada X tempo usando o método `scheduleAtFixedRate`.
+. You can schedule a task to run every X time using the `scheduleAtFixedRate` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Schedule_SingleThreadFixedRate.java
@@ -245,26 +243,25 @@ Depois da execução: 16:10:51.904
include::{section-java-package}/executetasks/Schedule_SingleThreadFixedRate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Antes do agendamento: 16:16:54.511
-Após do agendamento: 16:16:54.517
-Execução: 16:16:57.517
-Execução: 16:16:58.517
-Execução: 16:16:59.517
-Execução: 16:17:00.517
-Execução: 16:17:01.517
-Execução: 16:17:02.517
-Execução: 16:17:03.517
-Execução: 16:17:04.517
-Após o sleep de 10 segundos: 16:17:04.517
-Invocando shutdown no executor.
-----
-+
-Neste exemplos a execução demora 3 segundos para começar, e é repetida a cada 1 segundo, até o `shutdown` ser chamado. Por isso existe um `sleep` no final do bloco `try`, para garantir que enxergaríamos a execução da tarefa por algumas vezes antes de invocar o `shutdown`.
+Before Scheduling: 10:16:00.717
+After Scheduling: 10:16:00.727
+Execution: 10:16:03.731
+Execution: 10:16:04.728
+Execution: 10:16:05.727
+Execution: 10:16:06.727
+Execution: 10:16:07.731
+Execution: 10:16:08.733
+Execution: 10:16:09.730
+After 10 seconds sleep: 10:16:10.732
+Invoking shutdown on executor.
+----
++
+In these examples execution takes 3 seconds to begin, and is repeated every 1 second until `shutdown` is called. So there is a `sleep` at the end of the `try` block, to ensure that we would see the task running a few times before calling `shutdown`.
-. É possível agendar uma tarefa para ser executada X tempo após o término da tarefa anterior usando o método `scheduleWithFixedDelay`.
+. You can schedule a task to run X time after the previous task ends using the `scheduleWithFixedDelay` method.
+
[source,java,indent=0]
.{java-package}/executetasks/Schedule_SingleThreadFixedDelay.java
@@ -272,29 +269,29 @@ Neste exemplos a execução demora 3 segundos para começar, e é repetida a cad
include::{section-java-package}/executetasks/Schedule_SingleThreadFixedDelay.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Antes do agendamento: 16:20:46.717
-Após do agendamento: 16:20:46.727
-Execução: 16:20:49.728
-Execução: 16:20:50.729
-Execução: 16:20:51.729
-Execução: 16:20:52.730
-Execução: 16:20:53.731
-Execução: 16:20:54.732
-Execução: 16:20:55.732
-Após o sleep de 10 segundos: 16:20:56.728
-Invocando shutdown no executor.
+Before Scheduling: 10:19:49.955
+After Scheduling: 10:19:49.964
+Execution: 10:19:52.967
+Execution: 10:19:53.964
+Execution: 10:19:54.964
+Execution: 10:19:55.964
+Execution: 10:19:56.965
+Execution: 10:19:57.966
+Execution: 10:19:58.965
+After 10 seconds sleep: 10:19:59.966
+Invoking shutdown on executor.
----
+
-Este exemplo é muito parecido com o anterior, porém há uma diferença importante: a nova tarefa só começa a executar 1 segundo depois do *término* da anterior. No exemplo acima a tarefa era executada a *cada* 1 segundo, independente do término da anterior. Perceba as diferenças nos milissegundos.
+This example is very similar to the previous one, but there is one important difference: the new task only starts to run 1 second after the *end* of the previous one. In the example above the task was executed *every* 1 second, regardless of the end of the previous one. Note the differences in milliseconds.
-==== Múltiplas Threads
+==== Multiple Threads
-Todos os exemplos até agora utilizaram apenas uma _thread_ adicional. Em todos eles, seria possível utilizar construtores de `Executors` que fornecem mais de uma _thread_.
+All examples have so far used only one additional _thread_. In all of them, it would be possible to use `Executor` constructors that provide more than one _thread_.
-. É possível criar um Executor que cria _threads_ conforme o necessário, e as reutiliza quando possível, utilizando o método `newCachedThreadPool`.
+. You can create an Executor that creates _threads_ as needed, and reuses them when possible, using the `newCachedThreadPool` method.
+
[source,java,indent=0]
.{java-package}/executetasks/TasksMulti_CachedThreadPool.java
@@ -302,19 +299,19 @@ Todos os exemplos até agora utilizaram apenas uma _thread_ adicional. Em todos
include::{section-java-package}/executetasks/TasksMulti_CachedThreadPool.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa 1 - Thread do Executor: pool-1-thread-1
-Tarefa 2 - Thread do Executor: pool-1-thread-2
-Tarefa 3 - Thread do Executor: pool-1-thread-3
-Tarefa 4 - Thread do Executor: pool-1-thread-3
-Tarefa 5 - Thread do Executor: pool-1-thread-3
+Task 1 - Executor Thread: pool-1-thread-1
+Task 2 - Executor Thread: pool-1-thread-2
+Task 3 - Executor Thread: pool-1-thread-3
+Task 4 - Executor Thread: pool-1-thread-3
+Task 5 - Executor Thread: pool-1-thread-3
----
+
-Perceba que foram criadas 3 _threads_, e a terceira foi utilizada 3 vezes.
+Note that 3 _threads_ were created, and the third was used 3 times.
-. É possível criar um Executor com um número delimitado de _threads_ utilizando o método `newFixedThreadPool`.
+. You can create an Executor with a delimited number of _threads_ using the `newFixedThreadPool` method.
+
[source,java,indent=0]
.{java-package}/executetasks/TasksMulti_FixedThreadPool.java
@@ -322,17 +319,17 @@ Perceba que foram criadas 3 _threads_, e a terceira foi utilizada 3 vezes.
include::{section-java-package}/executetasks/TasksMulti_FixedThreadPool.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Tarefa 1 - Thread do Executor: pool-1-thread-1
-Tarefa 2 - Thread do Executor: pool-1-thread-2
-Tarefa 3 - Thread do Executor: pool-1-thread-1
-Tarefa 4 - Thread do Executor: pool-1-thread-2
-Tarefa 5 - Thread do Executor: pool-1-thread-1
+Task 1 - Executor Thread: pool-1-thread-1
+Task 2 - Executor Thread: pool-1-thread-2
+Task 3 - Executor Thread: pool-1-thread-1
+Task 4 - Executor Thread: pool-1-thread-2
+Task 5 - Executor Thread: pool-1-thread-1
----
-. É possível criar um Executor de agendamento com um número delimitado de _threads_ utilizando o método `newScheduledThreadPool`.
+. You can create a Scheduler with a delimited number of _threads_ using the `newScheduledThreadPool` method.
+
[source,java,indent=0]
.{java-package}/executetasks/TasksMulti_ScheduledThreadPool.java
@@ -340,24 +337,25 @@ Tarefa 5 - Thread do Executor: pool-1-thread-1
include::{section-java-package}/executetasks/TasksMulti_ScheduledThreadPool.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Agora: 16:33:36.825
-Execução 1: pool-1-thread-1 - 16:33:39.834
-Execução 2: pool-1-thread-2 - 16:33:39.836
-Execução 3: pool-1-thread-1 - 16:33:39.837
-Execução 4: pool-1-thread-1 - 16:33:39.838
-Execução 5: pool-1-thread-2 - 16:33:39.838
+Now: 16:33:36.825
+Execution 1: pool-1-thread-1 - 16:33:39.834
+Execution 2: pool-1-thread-2 - 16:33:39.836
+Execution 3: pool-1-thread-1 - 16:33:39.837
+Execution 4: pool-1-thread-1 - 16:33:39.838
+Execution 5: pool-1-thread-2 - 16:33:39.838
----
+
-Duas _threads_ e _delay_ de 3 segundos em todos os agendamentos.
+Two _threads_ and _delay_ of 3 seconds on all schedules.
+.References
****
* Creating Threads with the ExecutorService
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 335). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 335). Wiley. Kindle Edition.
* https://www.baeldung.com/thread-pool-java-and-guava[Introduction to Thread Pools in Java.]
@@ -365,4 +363,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* hhttps://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html[Interface ExecutorService.] Java Plataform SE 7.
-****
\ No newline at end of file
+****
diff --git a/book/06-concurrency/sections/04-fork-join.asc b/book/06-concurrency/sections/04-fork-join.asc
index e0b0672..e7fd919 100644
--- a/book/06-concurrency/sections/04-fork-join.asc
+++ b/book/06-concurrency/sections/04-fork-join.asc
@@ -1,30 +1,28 @@
:java-package: src/org/j6toj8/concurrency
:section-java-package: ../../../{java-package}
-=== Framework Fork/Join
+=== Fork/Join Framework
-.Objetivo
+.Objective
--------------------------------------------------
Use the parallel Fork/Join Framework
--
-Usar o Framework Fork/Join de paralelismo
--------------------------------------------------
-Com o framework de Fork/Join é possível dividir uma tarefa grande em pedaços menores e executá-los em paralelo. A utilização do framework é simples. A criação de tarefas quebradas em várias partes pode ser um pouco mais complexa.
+With the Fork/Join framework you can split a large task into smaller pieces and execute them in parallel. The use of the framework is simple. Creating broken tasks into several parts can be a bit more complex.
-Uma tarefa geralmente segue um comportamento padrão:
+A task usually follows a default behavior:
-* Recebe um valor;
-* Avalia se o valor é pequeno o suficiente para executar a tarefa com ele;
-** Caso positivo, executa a tarefa com aquele valor;
-** Caso negativo, quebra em uma ou mais partes e cria novas tarefas menores;
-* Segue executando de forma recursiva.
+* Receives a value;
+* Evaluates if the value is small enough to perform the task with it;
+** If so, execute the task with that value;
+** If not, it breaks into one or more parts and creates new smaller tasks;
+* Continues running recursively.
-Serão apresentados exemplos utilizando a classe `RecursiveAction`, que não retorna valores, e por isso sua implementação é mais simples. E utilizando a classe `RecursiveTask`, que retorna valores e por isso sua implementação é um pouco mais complexa.
+Examples will be presented using the `RecursiveAction` class, which returns no values, so its implementation is simpler. And using the `RecursiveTask` class, which returns values and so its implementation is a bit more complex.
-Os exemplos são grandes, pois é necessário implementar toda a classe `RecursiveAction` ou `RecursiveTask` para o exemplo funcionar. Por isso, os passos serão descritos com comentários no código, explicando o funcionamento de cada chamada realizada ao framework.
+The examples are large because you need to implement the entire `RecursiveAction` or `RecursiveTask` class for the example to work. Therefore, the steps will be described with comments in the code, explaining the operation of each call made to the framework.
-. É possível implementar uma `RecursiveAction` que divide uma tarefa grande em partes menores.
+. You can implement a `RecursiveAction` that divides a large task into smaller parts.
+
[source,java,indent=0]
.{java-package}/forkjoin/ForkJoin_RecursiveAction.java
@@ -32,7 +30,7 @@ Os exemplos são grandes, pois é necessário implementar toda a classe `Recursi
include::{section-java-package}/forkjoin/ForkJoin_RecursiveAction.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ForkJoinPool-1-worker-1 - ABCDEF
@@ -41,15 +39,15 @@ ForkJoinPool-1-worker-2 - NOPQRS
ForkJoinPool-1-worker-3 - GHIJKLM
----
+
-.. Esse exemplo cria uma tarefa do tipo `RecursiveAction` chamada `ImpressaoDeStrings`.
-.. Essa `RecursiveAction` recebe uma `String` para imprimir no Console.
-.. No método `compute`, a tarefa decide se irá imprimir diretamente no console, ou se irá dividir esse trabalho em duas partes: caso a `String` tenha menos que 10 caracteres, ela imprime diretamente no Console; caso contrário, divide o trabalho em duas novas tarefas.
+.. This example creates a task of type `RecursiveAction` called `StringPrinting`.
+.. This `RecursiveAction` gets a `String` to print to the Console.
+.. In the `compute` method, the job decides whether to print directly to the console, or to split this job into two parts: if the `String` is less than 10 characters long, it prints directly to the console; otherwise it splits the work into two new tasks.
+
-Perceba que cada impressão no console é realizada em uma _thread_ diferente, ficando claro que o trabalho está sendo compartilhado por múltiplas _threads_.
+Note that each print on the console is performed on a different _thread_, making it clear that the job is being shared by multiple _threads_.
+
-Perceba também que o processamento da String não retorna nenhum valor, e por isso foi utilizada a classe `RecursiveAction`.
+Also note that String processing returns no value, so the `RecursiveAction` class was used.
-. Caso seja necessário retornar um valor, é possível implementar uma `RecursiveTask` que divide uma tarefa grande em partes menores.
+. If you need to return a value, you can implement a `RecursiveTask` that divides a large task into smaller parts.
+
[source,java,indent=0]
.{java-package}/forkjoin/ForkJoin_RecursiveTask.java
@@ -57,7 +55,7 @@ Perceba também que o processamento da String não retorna nenhum valor, e por i
include::{section-java-package}/forkjoin/ForkJoin_RecursiveTask.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
ForkJoinPool-1-worker-3 - NOPQRS
@@ -67,21 +65,21 @@ ForkJoinPool-1-worker-1 - TUVWXYZ
Resultado da execução: 26
----
+
-.. Esse exemplo cria uma tarefa do tipo `RecursiveTask` chamada `ImpressaoDeStrings`.
-.. Essa `RecursiveTask` recebe uma `String` para imprimir no Console.
-.. No método `compute`, a tarefa decide se irá imprimir diretamente no console, ou se irá dividir esse trabalho em duas partes: caso a `String` tenha menos que 10 caracteres, ela imprime diretamente no Console; caso contrário, divide o trabalho em duas novas tarefas.
+.. This example creates a task of type `RecursiveTask` called `StringPrinting`.
+.. This `RecursiveTask` is given a `String` to print to the Console.
+.. In the `compute` method, the job decides whether to print directly to the console, or to split this job into two parts: if the `String` is less than 10 characters long, it prints directly to the console; otherwise it splits the work into two new tasks.
+
-Perceba também que o processamento da String retorna quantos caracteres foram impressos, e por isso foi utilizada a classe `RecursiveTask`.
-
+Also note that String processing returns how many characters were printed, so the `RecursiveTask` class was used.
+.References
****
* Managing Concurrent Processes
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 377). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 377). Wiley. Kindle Edition.
* https://www.baeldung.com/java-fork-join[Guide to the Fork/Join Framework in Java.]
* https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html[Fork/Join.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/07-file-io/sections/01-paths.asc b/book/07-file-io/sections/01-paths.asc
index 2ce3a2f..6c0b546 100644
--- a/book/07-file-io/sections/01-paths.asc
+++ b/book/07-file-io/sections/01-paths.asc
@@ -3,22 +3,20 @@
=== Paths
-.Objetivo
+.Objective
--------------------------------------------------
Operate on file and directory paths by using the Paths class
--
-Operar em arquivos e diretórios usando a classe Paths
--------------------------------------------------
-As classes `Path` e `Paths` são novidades do Java 7.
+The `Path` and `Paths` classes are new to Java 7.
-A classe `Path` representa um arquivo ou um diretório no sistema de arquivos, e a maioria das suas operações não altera diretamente arquivos ou diretórios.
+The `Path` class represents a file or directory in the file system, and most of its operations do not directly change files or directories.
-A classe `Paths` contém métodos estáticos para a criação de `Path`.
+The `Paths` class contains static methods for creating `Path`.
-Para que os exemplos executem independente do sistema, será utilizado o diretório do usuário, que no Java está disponível em uma propriedade da JVM chamada `user.home`.
+For the examples to run system-independent, the user directory will be used, which in Java is available in a JVM property called `user.home`.
-. Existem inúmeras formas de obter uma instância de `Path`.
+. There are numerous ways to get an instance of `Path`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Creation.java
@@ -26,7 +24,7 @@ Para que os exemplos executem independente do sistema, será utilizado o diretó
include::{section-java-package}/paths/Paths_Creation.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
@@ -42,7 +40,7 @@ Path 9: /home/rinaldo/arquivo.txt
Path 10: /home/rinaldo
----
-. É possível criar uma instância de `Path` apontando para um diretório ou arquivo que não existe.
+. You can create an instance of `Path` by pointing to a directory or file that does not exist.
+
[source,java,indent=0]
.{java-package}/paths/Paths_CreationDoesntExists.java
@@ -50,14 +48,14 @@ Path 10: /home/rinaldo
include::{section-java-package}/paths/Paths_CreationDoesntExists.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivoQueNaoExiste.txt
+Path: /home/rinaldo/fileThatDoesNotExist.txt
----
-. É possível converter um `Path` para um `File`.
+. It is possible to convert a `Path` to a `File`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToFile.java
@@ -65,15 +63,15 @@ Path: /home/rinaldo/arquivoQueNaoExiste.txt
include::{section-java-package}/paths/Paths_ToFile.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivoQueNaoExiste.txt
-File: /home/rinaldo/arquivoQueNaoExiste.txt
+Path: /home/rinaldo/fileThatDoesNotExist.txt
+File: /home/rinaldo/fileThatDoesNotExist.txt
----
-. Existem inúmeros método no `Path` para recuperar informações a seu respeito.
+. There are numerous methods in `Path` to retrieve information about it.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Information.java
@@ -81,25 +79,25 @@ File: /home/rinaldo/arquivoQueNaoExiste.txt
include::{section-java-package}/paths/Paths_Information.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Representação em String: /home/rinaldo/arquivos/arquivo.txt
-Nome do Arquivo: arquivo.txt
-Diretório Superior: /home/rinaldo/arquivos
-Diretório Raiz: /
-É absoluto? true
+String representation: /home/rinaldo/files/file.txt
+File Name: file.txt
+Top Directory: /home/rinaldo/files
+Root Directory: /
+Is it absolute?: true
-Representação em String: home/rinaldo/arquivos
-Nome do Arquivo: arquivos
-Diretório Superior: home/rinaldo
-Diretório Raiz: null
-É absoluto? false
+String representation: home/rinaldo/files
+File Name: files
+Top Directory: home/rinaldo
+Root Directory: null
+Is it absolute?: false
----
-. É possível recuperar os elementos do `Path` individualmente.
+. It is possible to retrieve the elements of `Path` individually.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Names.java
@@ -107,18 +105,18 @@ Diretório Raiz: null
include::{section-java-package}/paths/Paths_Names.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
home
rinaldo
-arquivos
-arquivo.txt
+files
+file.txt
----
-. É possível converter um `Path` relativo para um absoluto.
+. It is possible to convert a relative `Path` to an absolute.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToAbsolute.java
@@ -126,19 +124,19 @@ arquivo.txt
include::{section-java-package}/paths/Paths_ToAbsolute.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-arquivos
-É absoluto? false
+files
+Is it absolute? false
-/home/rinaldo/Desenvolvimento/git/java6-to-java8/arquivos
-É absoluto? true
+/home/rinaldo/Desenvolvimento/git/java6-to-java8/files
+Is it absolute? true
----
+
-Neste caso a saída do console vai depende do diretório onde a aplicação está sendo executada.
+In this case the console output will depend on the directory where the application is running.
-. É possível criar _Sub-Paths_ a partir de um `Path`.
+. You can create _Sub-Paths_ from a `Path`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_SubPath.java
@@ -146,22 +144,22 @@ Neste caso a saída do console vai depende do diretório onde a aplicação est
include::{section-java-package}/paths/Paths_SubPath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivos/arquivo1.txt
+Path: /home/rinaldo/arquivos/file1.txt
home
home/rinaldo
-rinaldo/arquivos
-arquivos/arquivo1.txt
+rinaldo/files
+arquivos/file1.txt
Exception in thread "main" java.lang.IllegalArgumentException
at sun.nio.fs.UnixPath.subpath(UnixPath.java:348)
at sun.nio.fs.UnixPath.subpath(UnixPath.java:43)
at org.j6toj8.fileio.paths.Paths_SubPath.main(Paths_SubPath.java:28)
----
-. É possível remover redundâncias de um `Path` com o método `normalize`.
+. You can remove redundancies from a `Path` with the `normalize` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Normalize.java
@@ -169,19 +167,19 @@ Exception in thread "main" java.lang.IllegalArgumentException
include::{section-java-package}/paths/Paths_Normalize.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivos/./arquivo1.txt
-Path normalize: /home/rinaldo/arquivos/arquivo1.txt
+Path: /home/rinaldo/files/./file1.txt
+Path normalize: /home/rinaldo/files/file1.txt
-Path: /home/rinaldo/arquivos/../arquivo1.txt
-Path normalize: /home/rinaldo/arquivo1.txt
+Path: /home/rinaldo/files/../file1.txt
+Path normalize: /home/rinaldo/file1.txt
----
-. É possível unir duas instâncias de `Path` com o método `resolve`.
+. You can join two instances of `Path` with the `resolve` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Resolve.java
@@ -189,22 +187,22 @@ Path normalize: /home/rinaldo/arquivo1.txt
include::{section-java-package}/paths/Paths_Resolve.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Absoluto + Relativo: /home/rinaldo/arquivos/arquivo1.txt
-Relativo + Absoluto: /home/rinaldo/arquivos
-Absoluto + Absoluto: /home/rinaldo/arquivos
-Relativo + Relativo: arquivo1.txt/arquivo1.txt
+Absolute + Relative: /home/rinaldo/files/file1.txt
+Relative + Absolute: /home/rinaldo/files
+Absolute + Absolute: /home/rinaldo/files
+Relative + Relative: file1.txt/file1.txt
----
+
-Perceba que sempre que o argumento é um `Path` absoluto, o resultado final é ele mesmo.
+Note that whenever the argument is an absolute `Path`, the end result is itself.
+
-Quando o argumento é um `Path` relativo, ele é acrescentado ao original, seja este absoluto ou relativo.
+When the argument is a relative `Path`, it is appended to the original, either absolute or relative.
-. É possível derivar um `Path` de outro com o método `relativize`.
+. It is possible to derive one `Path` from another with the `relativize` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Relativize.java
@@ -212,19 +210,19 @@ Quando o argumento é um `Path` relativo, ele é acrescentado ao original, seja
include::{section-java-package}/paths/Paths_Relativize.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Absoluto 1: /home/rinaldo/arquivos
-Absoluto 2: /home/rinaldo/arquivos/arquivo1.txt
-Relativo 1: arquivo1.txt
-Relativo 2: arquivos/arquivo1.txt
-Absoluto 1 + Absoluto 2: arquivo1.txt
-Absoluto 2 + Absoluto 1: ..
-Relativo 1 + Relativo 2: ../arquivos/arquivo1.txt
-Relativo 2 + Relativo 1: ../../arquivo1.txt
+Absolute 1: /home/rinaldo/files
+Absolute 2: /home/rinaldo/files/file1.txt
+Relative 1: file1.txt
+Relative 2: files/file1.txt
+Absolute 1 + Absolute 2: file1.txt
+Absolute 2 + Absolute 1: ..
+Relative 1 + Relative 2: ../files/file1.txt
+Relative 2 + Relative 1: ../../file1.txt
java.lang.IllegalArgumentException: 'other' is different type of Path
at sun.nio.fs.UnixPath.relativize(UnixPath.java:416)
at sun.nio.fs.UnixPath.relativize(UnixPath.java:43)
@@ -235,9 +233,9 @@ java.lang.IllegalArgumentException: 'other' is different type of Path
at org.j6toj8.fileio.paths.Paths_Relativize.main(Paths_Relativize.java:40)
----
+
-Todas essas combinações podem aparecere no exame, então entenda bem como cada uma delas se comporta. Lembre-se principalmente de que não é possível derivar um `Path` absoluto de um relativo, e vice-versa.
+All of these combinations may appear on the exam, so understand well how each one behaves. Remember especially that it is not possible to derive an absolute `Path` from a relative, and vice versa.
-. É possível converter um `Path` sintético, que não aponta de fato para um arquivo no sistema de arquivos, em um `Path` real, que aponta para um arquivo ou diretório que existe no sistema de arquivos.
+. It is possible to convert a synthetic `Path`, which does not actually point to a file in the file system, into a real `Path`, which points to a file or directory that exists in the file system.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToRealPath.java
@@ -245,12 +243,12 @@ Todas essas combinações podem aparecere no exame, então entenda bem como cada
include::{section-java-package}/paths/Paths_ToRealPath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-realPath: /home/rinaldo/arquivo1.txt
-java.nio.file.NoSuchFileException: /home/rinaldo/arquivoQueNaoExiste.txt
+realPath: /home/rinaldo/file1.txt
+java.nio.file.NoSuchFileException: /home/rinaldo/fileThatDoesNotExist.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
@@ -258,13 +256,14 @@ java.nio.file.NoSuchFileException: /home/rinaldo/arquivoQueNaoExiste.txt
at org.j6toj8.fileio.paths.Paths_ToRealPath.main(Paths_ToRealPath.java:25)
----
+
-Perceba que é lançada exceção caso o arquivo realmente não exista no sistema de arquivos.
+Note that an exception is thrown if the file does not actually exist in the file system.
+.References
****
* Introducing NIO.2
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Kindle Edition.
* https://www.baeldung.com/java-nio-2-path[Java NIO2 Path API.]
@@ -272,4 +271,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html[Path Operations.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/07-file-io/sections/02-files.asc b/book/07-file-io/sections/02-files.asc
index c1b9317..6b76371 100644
--- a/book/07-file-io/sections/02-files.asc
+++ b/book/07-file-io/sections/02-files.asc
@@ -3,16 +3,14 @@
=== Files
-.Objetivo
+.Objective
--------------------------------------------------
Check, delete, copy, or move a file or directory by using the Files class
--
-Checar, deletar, copiar ou mover um arquivo ou diretório utilizando a classe Files
--------------------------------------------------
-A classe `Files` contém inúmeros métodos estáticos para lidar com instâncias de ``Path``. A maioria dos métodos recebem instâncias de `Path` para realizar alguma operação no arquivo ou diretório representado pelo ``Path``. Muitos irão lançar uma exceção caso o arquivo ou diretório não exista no sistema de arquivos.
+The `Files` class contains numerous static methods for handling `Path` instances. Most methods receive instances of `Path` to perform some operation on the file or directory represented by `Path`. Many will throw an exception if the file or directory does not exist in the file system.
-. É possível checar vários atributos de um `Path` utilizando a classe `Files`.
+. You can check various attributes of a `Path` using the `Files` class.
+
[source,java,indent=0]
.{java-package}/files/Files_Checks.java
@@ -20,29 +18,29 @@ A classe `Files` contém inúmeros métodos estáticos para lidar com instância
include::{section-java-package}/files/Files_Checks.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path 1: /home/rinaldo/arquivo1.txt
-Path 2: /home/rinaldo/arquivos
-Path 1 existe? true
-Path 2 existe? false
-Path 1 NÃO existe? false
-Path 2 NÃO existe? true
-Path 1 é um diretório? false
-Path 1 é um arquivo comum? true
-Path 1 é um link simbólico? false
-Aplicação possui permissão de leitura no Path 1? true
-Aplicação possui permissão de escrita no Path 1? true
-Aplicação possui permissão de execução no Path 1? false
-Path 1 é oculto? false
-Path 1 e Path 1 são iguais? true
-----
-+
-Perceba que algumas chamadas lançam `IOException`. Isso ocorre pois elas irão lançar essa exceção caso o `Path` não exista no sistema de arquivos.
+Path 1: /home/rinaldo/file1.txt
+Path 2: /home/rinaldo/files
+Path 1 exist? true
+Path 2 exist? false
+Path 1 does NOT exist? false
+Path 2 does NOT exist? true
+Is Path 1 a directory? false
+Is Path 1 a common file? true
+Is Path 1 a symbolic link? false
+Application has read permission on Path 1? true
+Application has write permission on Path 1? true
+Application has execution permission on Path 1? false
+Is Path 1 hidden? false
+Are Path 1 and Path 1 the same? true
+----
++
+Note that some calls throw `IOException`. This is because they will throw this exception if `Path` does not exist in the file system.
-. É possível verificar se dois ``Path``'s são iguais, mesmo que estejam representados de forma diferente.
+. You can verify that two ``Path```s are the same even if they are represented differently.
+
[source,java,indent=0]
.{java-package}/files/Files_SameFile.java
@@ -50,19 +48,19 @@ Perceba que algumas chamadas lançam `IOException`. Isso ocorre pois elas irão
include::{section-java-package}/files/Files_SameFile.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path 1 e Path 2 são iguais? true
-Path 2 e Path 3 são iguais? true
-Path 3 e Path 4 são iguais? true
-Path 1 e Path 4 são iguais? true
+Are Path 1 and Path 2 the same? true
+Are Path 2 and Path 3 the same? true
+Are Path 3 and Path 4 the same? true
+Are Path 1 and Path 4 the same? true
----
+
-Perceba que nesse exemplo todos os `Path` são iguais, pois apontam para o mesmo arquivo. Ou seja, o método realmetne verifica se o arquivo no sistema de arquivos é o mesmo, indepenente da forma como o diretório está sendo representado no `Path`. Isso funcionará inclusive para links simbólicos que apontam para o mesmo arquivo.
+Note that in this example all `Path` are the same as they point to the same file. That is, the method actually checks if the file in the file system is the same regardless of how the directory is being represented in `Path`. This will even work for symbolic links that point to the same file.
-. É possível criar arquivos utilizando a classe `Files`.
+. You can create files using the `Files` class.
+
[source,java,indent=0]
.{java-package}/files/Files_CreateFile.java
@@ -70,16 +68,16 @@ Perceba que nesse exemplo todos os `Path` são iguais, pois apontam para o mesmo
include::{section-java-package}/files/Files_CreateFile.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo8481614.txt
-Path existe? false
-Path existe? true
+Path: /home/rinaldo/file8481614.txt
+Path exist? false
+Path exist? true
----
-. É possível criar um diretório utilizando a classe `Files`.
+. You can create a directory using the `Files` class.
+
[source,java,indent=0]
.{java-package}/files/Files_CreateDirectory.java
@@ -87,16 +85,16 @@ Path existe? true
include::{section-java-package}/files/Files_CreateDirectory.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo411247666
-Path existe? false
-Path existe? true
+Path: /home/rinaldo/file411247666
+Path exist? false
+Path exist? true
----
-. Caso o `Path` possua vários elementos a serem criados, é necessário utilizar o método `createDirectories`, no plural, caso contrário será lançada uma exceção.
+. If `Path` has multiple elements to create, you must use the `createDirectories` method, otherwise an exception will be thrown.
+
[source,java,indent=0]
.{java-package}/files/Files_CreateDirectories.java
@@ -104,23 +102,23 @@ Path existe? true
include::{section-java-package}/files/Files_CreateDirectories.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo783746545/arquivo248290405/arquivo801162958
-java.nio.file.NoSuchFileException: /home/rinaldo/arquivo783746545/arquivo248290405/arquivo801162958
+Path: /home/rinaldo/file783746545/file248290405/file801162958
+java.nio.file.NoSuchFileException: /home/rinaldo/arquivo783746545/arquivo248290405/file801162958
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:384)
at java.nio.file.Files.createDirectory(Files.java:674)
at org.j6toj8.fileio.files.Files_CreateDirectories.main(Files_CreateDirectories.java:26)
-Path existe? false
-Path existe? true
+Path exist? false
+Path exist? true
----
-. É possível copiar uma arquivo ou diretório.
+. You can copy a file or directory.
+
[source,java,indent=0]
.{java-package}/files/Files_CopyPath.java
@@ -128,23 +126,23 @@ Path existe? true
include::{section-java-package}/files/Files_CopyPath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path 1: /home/rinaldo/arquivo-1156333590.txt
-Path 2: /home/rinaldo/arquivo-1156333590.txt-copia.txt
-Path 1 existe? false
-Path 1 existe? true
-Path 2 existe? false
-Path 2 existe? true
+Path 1: /home/rinaldo/file-1156333590.txt
+Path 2: /home/rinaldo/file-1156333590.txt-copy.txt
+Path 1 exist? false
+Path 1 exist? true
+Path 2 exist? false
+Path 2 exist? true
----
+
-Ao copiar um arquivo, é necessário que os diretórios já existam, caso contrário será lançada uma exceção.
+When copying a file, directories must already exist, otherwise an exception will be thrown.
+
-Ao copiar um diretório, o conteúdo dele não será copiado.
+When copying a directory, its contents will not be copied.
-. É possível copiar a partir de um `FileInputStream` para um `Path`.
+. It is possible to copy from a `FileInputStream` to a `Path`.
+
[source,java,indent=0]
.{java-package}/files/Files_CopyToPath.java
@@ -152,15 +150,15 @@ Ao copiar um diretório, o conteúdo dele não será copiado.
include::{section-java-package}/files/Files_CopyToPath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path 2 existe? false
-Path 2 existe? true
+Path 2 exist? false
+Path 2 exist? true
----
-. É possível copiar para um `FileOutputStream` a partir de `Path`.
+. You can copy to a `FileOutputStream` from `Path`.
+
[source,java,indent=0]
.{java-package}/files/Files_CopyFromPath.java
@@ -168,15 +166,15 @@ Path 2 existe? true
include::{section-java-package}/files/Files_CopyFromPath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path criado: /home/rinaldo/copia860242436.txt
-Path criado existe?: true
+Created Path: /home/rinaldo/copy860242436.txt
+Created Path exist? true
----
-. Também é possível mover um `Path`, seja ele um diretório ou um arquivo.
+. It is also possible to move a `Path`, either a directory or a file.
+
[source,java,indent=0]
.{java-package}/files/Files_MoveFile.java
@@ -184,24 +182,24 @@ Path criado existe?: true
include::{section-java-package}/files/Files_MoveFile.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path Arquivo Origem: /home/rinaldo/arquivo-2044553267.txt
-Path Arquivo Destino: /home/rinaldo/arquivo-2044553267.txt-movido.txt
-Arquivo origem existe? false
-Arquivo origem existe? true
-Arquivo destino existe? false
-Arquivo destino existe? true
-Arquivo origem existe? false
+Path Source File: /home/rinaldo/file-2044553267.txt
+Path Destination File: /home/rinaldo/file-2044553267.txt-moved.txt
+Source File exist? false
+Source File exist? true
+Destination File exist? false
+Destination File exist? true
+Source File exist? false
----
+
-Ao mover um diretório, o conteúdo será movido também.
+When you move a directory, the content will be moved as well.
+
-Ao mover um `Path` para um diretório que não exista, será lançado exceção.
+Moving a `Path` to a non-existent directory will throw an exception.
-. É possível apagar um `Path`.
+. It is possible to delete a `Path`.
+
[source,java,indent=0]
.{java-package}/files/Files_DeletePath.java
@@ -209,22 +207,22 @@ Ao mover um `Path` para um diretório que não exista, será lançado exceção.
include::{section-java-package}/files/Files_DeletePath.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo-113782412.txt
-Path existe? false
-Path existe? true
-Path existe? false
-Path existe? false
+Path: /home/rinaldo/file-113782412.txt
+Path exist? false
+Path exist? true
+Path exist? false
+Path exist? false
----
+
-Perceba que existem dois métodos diferentes para apagar. O primeira irá lançar exceção se o arquivo não existir, o segundo não irá lançar.
+Note that there are two different methods for erasing. The first will throw exception if the file does not exist, the second will not throw.
+
-Ao tentar apagar um diretório com conteúdo será lançada uma exceção.
+Attempting to delete a directory with content will throw an exception.
-. É possível escrever e ler arquivos com `Files` e `Path`.
+. You can write and read files with `Files` and `Path`.
+
[source,java,indent=0]
.{java-package}/files/Files_WriteFile.java
@@ -232,19 +230,19 @@ Ao tentar apagar um diretório com conteúdo será lançada uma exceção.
include::{section-java-package}/files/Files_WriteFile.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo-1467732927.txt
-Path existe? false
-Path existe? true
+Path: /home/rinaldo/file-1467732927.txt
+Path exist? false
+Path exist? true
123
----
+
-Perceba que primeiro foi criado o arquivo. Depois ele foi escrito com um `BufferedWriter`. E depois foi lido com um `BufferedReader`.
+Note that the file was first created. Then it was written with a `BufferedWriter`. And then it was read with a `BufferedReader`.
-. É possível ler todas as linhas de um arquivo com uma única chamada.
+. You can read all lines of a file with a single call.
+
[source,java,indent=0]
.{java-package}/files/Files_ReadAllLines.java
@@ -252,7 +250,7 @@ Perceba que primeiro foi criado o arquivo. Depois ele foi escrito com um `Buffer
include::{section-java-package}/files/Files_ReadAllLines.java[tag=code]
----
+
-.arquivo.txt
+.file.txt
[source]
----
1
@@ -262,14 +260,14 @@ include::{section-java-package}/files/Files_ReadAllLines.java[tag=code]
5
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
[1, 2, 3, 4, 5]
----
-. É possível verificar e alterar a data de modificação de um `Path`.
+. You can check and change the modification date of a `Path`.
+
[source,java,indent=0]
.{java-package}/files/Files_LastModified.java
@@ -277,16 +275,16 @@ User home: /home/rinaldo
include::{section-java-package}/files/Files_LastModified.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo805496635.txt
-Data de Modificação: 2019-08-14T18:53:23.710066Z
-Data de Modificação: 2019-08-14T18:53:33.724Z
+Path: /home/rinaldo/file805496635.txt
+Date Modified: 2019-08-14T18:53:23.710066Z
+Date Modified: 2019-08-14T18:53:33.724Z
----
-. É possível modificar o _Owner_ (autor/dono) do arquivo.
+. You can modify the _Owner_ of the file.
+
[source,java,indent=0]
.{java-package}/files/Files_Owner.java
@@ -294,18 +292,18 @@ Data de Modificação: 2019-08-14T18:53:33.724Z
include::{section-java-package}/files/Files_Owner.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Path: /home/rinaldo/arquivo-2139809923.txt
+Path: /home/rinaldo/file-2139809923.txt
rinaldo
rinaldo
----
+
-Perceba que é necessário utilizar as classes `UserPrincipalLookupService` e `UserPrincipal` para buscar um usuário no sistema e atribuí-lo como novo _Owner_. Essas operações podem depender da permissão do usuário, e por isso podem lançar exceção caso não possam ser executadas.
+Note that you must use the `UserPrincipalLookupService` and `UserPrincipal` classes to fetch a user from the system and assign them as new _Owner_. These operations may depend on the user's permission, and so may throw exceptions if they cannot be performed.
-. É possível recuperar todos os atributos de um arquivo com uma única chamada, utilizando a classe `BasicFileAttributes`.
+. You can retrieve all attributes of a file with a single call using the `BasicFileAttributes` class.
+
[source,java,indent=0]
.{java-package}/files/Files_BasicFileAttributes.java
@@ -313,23 +311,23 @@ Perceba que é necessário utilizar as classes `UserPrincipalLookupService` e `U
include::{section-java-package}/files/Files_BasicFileAttributes.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Tamanho: 10
-É diretório? false
-É link simbólico? false
-É um arquivo comum? true
-Não é nenhuma das opções acima? false
-Data de Criação: 2019-08-14T18:45:44.189475Z
-Último acesso: 2019-08-14T18:45:44.205475Z
-Última modificação: 2019-08-14T18:45:44.189475Z
+Size: 10
+Is it directory? false
+Is it symbolic link? false
+Is it a common file? true
+Not any of the above? false
+Creation date: 2019-08-14T18:45:44.189475Z
+Last acess: 2019-08-14T18:45:44.205475Z
+Last Modified: 2019-08-14T18:45:44.189475Z
----
+
-Utilizar a classe `BasicFileAttributes` para recuperar os atributos de um arquivo pode trazer ganhos de performance, já que é necessária apenas uma ida ao sistema operacional para recuperar todos os atributos.
+Using the `BasicFileAttributes` class to retrieve the attributes of a file can bring performance gains, since only one trip to the operating system is required to retrieve all attributes.
-. É possível modificar as datas de criação, modificação e acesso do arquivo com a classe `BasicFileAttributeView`.
+. You can modify file creation, modification, and access dates with the `BasicFileAttributeView` class.
+
[source,java,indent=0]
.{java-package}/files/Files_BasicFileAttributeView.java
@@ -337,27 +335,28 @@ Utilizar a classe `BasicFileAttributes` para recuperar os atributos de um arquiv
include::{section-java-package}/files/Files_BasicFileAttributeView.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
User home: /home/rinaldo
-Data de Criação original: 2019-08-14T19:24:04.548Z
-Último acesso original: 2019-08-14T19:24:04.548Z
-Última modificação original: 2019-08-14T19:24:04.548Z
+Original creation date: 2019-08-14T19:24:04.548Z
+Original last access: 2019-08-14T19:24:04.548Z
+Original last modified: 2019-08-14T19:24:04.548Z
-Data de Criação alterada: 2019-08-14T19:24:32.995Z
-Último acesso alterada: 2019-08-14T19:24:32.995Z
-Última modificação alterada: 2019-08-14T19:24:32.995Z
+Creation date changed: 2019-08-14T19:24:32.995Z
+Last access changed: 2019-08-14T19:24:32.995Z
+Last modified changed: 2019-08-14T19:24:32.995Z
----
+
-Perceba que a partir da classe `BasicFileAttributeView` também é possível ler os atributos do arquivo chamando o método `readAttributes`.
+Note that from the `BasicFileAttributeView` class you can also read the file attributes by calling the `readAttributes` method.
+.References
****
* Introducing NIO.2
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Kindle Edition.
* https://www.baeldung.com/java-nio-2-file-api[Introduction to the Java NIO2 File API.]
@@ -365,4 +364,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html[Path Operations.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/07-file-io/sections/03-recursive-access.asc b/book/07-file-io/sections/03-recursive-access.asc
index d9644f6..e78db9c 100644
--- a/book/07-file-io/sections/03-recursive-access.asc
+++ b/book/07-file-io/sections/03-recursive-access.asc
@@ -1,18 +1,16 @@
:java-package: src/org/j6toj8/fileio
:section-java-package: ../../../{java-package}
-=== DirectoryStream e FileVisitor
+=== DirectoryStream and FileVisitor
-.Objetivo
+.Objective
--------------------------------------------------
Recursively access a directory tree by using the DirectoryStream and FileVisitor interfaces
--
-Acessar recursivamente uma árvore de diretório usando as interfaces DirectoryStream e FileVisitor
--------------------------------------------------
-Nestão seção serão apresentadas duas classes para percorrer diretórios: `DirectoryStream` e `FileVisitor`.
+In this section we will present two classes for traversing directories: `DirectoryStream` and `FileVisitor`.
-. É possível checar vários atributos de um `Path` utilizando a classe `Files`.
+. You can check various attributes of a `Path` using the `Files` class.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_DirectoryStream.java
@@ -20,30 +18,30 @@ Nestão seção serão apresentadas duas classes para percorrer diretórios: `Di
include::{section-java-package}/recursiveaccess/Recursive_DirectoryStream.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/arquivo2.txt
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/arquivo2.txt
+Path: /home/rinaldo/files
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/file2.txt
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/file2.txt
----
+
-Perceba que a instância de `DirectoryStream`:
+Note that the instance of `DirectoryStream`:
+
-* Pode ser utilizada com try-with-resources.
-* Pode ser iterada com a sintaxe de for-each.
-* Pode ser iterada com o método `forEach` que recebe uma expressão lambda.
-* Lança exceção caso o arquivo não exista.
-* Não lista os subdiretórios de forma recursiva, mas sim apenas o primeiro nível.
-* Não tem relação com a API de _Streams_ do Java 8.
+* Can be used with try-with-resources.
+* Can be iterated with for-each syntax.
+* Can be iterated with the `forEach` method that receives a lambda expression.
+* Throws exception if the file does not exist.
+* Do not list subdirectories recursively, but only the first level.
+* Not related to the Java 8 _Streams_ API.
-. É possível acessar toda uma árvore de diretórios utilizando um `FileVisitor`.
+. You can access an entire directory tree using a `FileVisitor`.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_SimpleFileVisitor.java
@@ -51,25 +49,25 @@ Perceba que a instância de `DirectoryStream`:
include::{section-java-package}/recursiveaccess/Recursive_SimpleFileVisitor.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo122.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo121.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo11.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo12.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo13.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt. Tamanho: 2
+Path: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt. Size: 2
+Visited file: /home/rinaldo/files/file3.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file122.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file121.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/file11.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/file12.txt. Size: 2
+Visited file: /home/rinaldo/files/subfolder1/file13.txt. Size: 2
+Visited file: /home/rinaldo/files/file2.txt. Size: 2
----
+
-Perceba que todos os arquivos do diretório e subdiretórios foram visitados e impressos no console ao invocar `Files.walkFileTree`. Para cada arquivo encontrado foi invocado o método `visitFile` da instância de `MeuFileVisitor`.
+Note that all files in the directory and subdirectories were visited and printed on the console by invoking `Files.walkFileTree`. For each file found the `visitFile` method of the instance of `MyFileVisitor` was invoked.
+
-Veja que foi retornado `FileVisitResult.CONTINUE` do método `visitFile`. Isso instrui o FileVisitor a continuar visitando a árvore de arquivos. Também é possível retornar `TERMINATE`, `SKIP_SUBTREE` e `SKIP_SIBLINGS`, que serão apresentados a seguir.
+Note that `FileVisitResult.CONTINUE` has been returned from the `visitFile` method. This instructs FileVisitor to continue visiting the file tree. You can also return `TERMINATE`, `SKIP_SUBTREE` and `SKIP_SIBLINGS`, which will be shown below.
-. É possível finalizar a visitação quando for necessário retornando `FileVisitResult.TERMINATE`.
+. You can end the visit when needed by returning `FileVisitResult.TERMINATE`.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_VisitorTerminate.java
@@ -77,17 +75,17 @@ Veja que foi retornado `FileVisitResult.CONTINUE` do método `visitFile`. Isso i
include::{section-java-package}/recursiveaccess/Recursive_VisitorTerminate.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo122.txt. Tamanho: 10
-Arquivo encontrado. Finalizando.
+Path: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt. Size: 2
+Visited file: /home/rinaldo/files/file3.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file122.txt. Size: 10
+File found. Terminating.
----
-. Também é possível tomar decisões antes e depois de visitar diretórios.
+. It is also possible to make decisions before and after visiting directories.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_VisitorDirectory.java
@@ -95,19 +93,19 @@ Arquivo encontrado. Finalizando.
include::{section-java-package}/recursiveaccess/Recursive_VisitorDirectory.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo11.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo12.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo13.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt. Tamanho: 2
+Path: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt. Size: 2
+Visited file: /home/rinaldo/files/file3.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/file11.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/file12.txt. Size: 2
+Visited file: /home/rinaldo/files/subfolder1/file13.txt. Size: 2
+Visited file: /home/rinaldo/files/file2.txt. Size: 2
----
-. Também é possível ignorar todos os elementos que estão no mesmo nível de um `Path`.
+. You can also ignore all elements that are on the same level as a `Path`.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_VisitorIgnoreSiblings.java
@@ -115,19 +113,19 @@ Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt. Tamanho: 2
include::{section-java-package}/recursiveaccess/Recursive_VisitorIgnoreSiblings.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt. Tamanho: 2
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo122.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo121.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo11.txt. Tamanho: 10
-Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt. Tamanho: 2
+Path: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt. Size: 2
+Visited file: /home/rinaldo/files/file3.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file122.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file121.txt. Size: 10
+Visited file: /home/rinaldo/files/subfolder1/file11.txt. Size: 10
+Visited file: /home/rinaldo/files/file2.txt. Size: 2
----
-. É possível implementar diretamente a interface `FileVisitor`, ao invés de `SimpleFileVisitor`, e implementar todos os seus métodos.
+. You can directly implement the `FileVisitor` interface, instead of `SimpleFileVisitor`, and implement all of its methods.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_FileVisitor.java
@@ -135,29 +133,29 @@ Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt. Tamanho: 2
include::{section-java-package}/recursiveaccess/Recursive_FileVisitor.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Antes de visitar o diretório: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt
-Antes de visitar o diretório: /home/rinaldo/arquivos/subpasta1
-Antes de visitar o diretório: /home/rinaldo/arquivos/subpasta1/subpasta12
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo122.txt
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12/arquivo121.txt
-Após de visitar o diretório: /home/rinaldo/arquivos/subpasta1/subpasta12
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo11.txt
-Antes de visitar o diretório: /home/rinaldo/arquivos/subpasta1/subpasta11
-Após de visitar o diretório: /home/rinaldo/arquivos/subpasta1/subpasta11
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo12.txt
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo13.txt
-Após de visitar o diretório: /home/rinaldo/arquivos/subpasta1
-Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt
-Após de visitar o diretório: /home/rinaldo/arquivos
-----
-
-. É possível definir opções adicionais e limitar a profundidade utilizando outra versão do método `walkFileTree`.
+Path: /home/rinaldo/files
+Before visiting the directory: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt
+Visited file: /home/rinaldo/files/file3.txt
+Before visiting the directory: /home/rinaldo/files/subfolder1
+Before visiting the directory: /home/rinaldo/files/subfolder1/subfolder12
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file122.txt
+Visited file: /home/rinaldo/files/subfolder1/subfolder12/file121.txt
+After visiting the directory: /home/rinaldo/files/subfolder1/subfolder12
+Visited file: /home/rinaldo/files/subfolder1/file11.txt
+Before visiting the directory: /home/rinaldo/files/subfolder1/subfolder11
+After visiting the directory: /home/rinaldo/files/subfolder1/subfolder11
+Visited file: /home/rinaldo/files/subfolder1/file12.txt
+Visited file: /home/rinaldo/files/subfolder1/file13.txt
+After visiting the directory: /home/rinaldo/files/subfolder1
+Visited file: /home/rinaldo/files/file2.txt
+After visiting the directory: /home/rinaldo/files
+----
+
+. You can set additional options and limit depth using another version of the `walkFileTree` method.
+
[source,java,indent=0]
.{java-package}/recursiveaccess/Recursive_VisitorOptionsAndDepth.java
@@ -165,25 +163,26 @@ Após de visitar o diretório: /home/rinaldo/arquivos
include::{section-java-package}/recursiveaccess/Recursive_VisitorOptionsAndDepth.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Arquivo visitado: /home/rinaldo/arquivos/arquivo1.txt
-Arquivo visitado: /home/rinaldo/arquivos/arquivo3.txt
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta12
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo11.txt
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/subpasta11
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo12.txt
-Arquivo visitado: /home/rinaldo/arquivos/subpasta1/arquivo13.txt
-Arquivo visitado: /home/rinaldo/arquivos/arquivo2.txt
+Path: /home/rinaldo/files
+Visited file: /home/rinaldo/files/file1.txt
+Visited file: /home/rinaldo/files/file3.txt
+Visited file: /home/rinaldo/files/subfolder1/subfolder12
+Visited file: /home/rinaldo/files/subfolder1/file11.txt
+Visited file: /home/rinaldo/files/subfolder1/subfolder11
+Visited file: /home/rinaldo/files/subfolder1/file12.txt
+Visited file: /home/rinaldo/files/subfolder1/file13.txt
+Visited file: /home/rinaldo/files/file2.txt
----
+.References
****
* Working with Directories
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 617). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 617). Wiley. Kindle Edition.
* https://www.baeldung.com/java-list-directory-files[List Files in a Directory in Java.]
@@ -195,4 +194,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html[Path Operations.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/07-file-io/sections/04-file-improvements.asc b/book/07-file-io/sections/04-file-improvements.asc
index ab3dbaa..361b9aa 100644
--- a/book/07-file-io/sections/04-file-improvements.asc
+++ b/book/07-file-io/sections/04-file-improvements.asc
@@ -1,18 +1,16 @@
:java-package: src/org/j6toj8/fileio
:section-java-package: ../../../{java-package}
-=== Files com Streams
+=== Files with Streams
-.Objetivo
+.Objective
--------------------------------------------------
Find a file by using the PathMatcher interface, and use Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods
--
-Encontrar um arquivo usando a interface PathMatcher, e usar as melhorias de I/O do Java SE 8, incluindo os métodos Files.find(), Files.walk(), and lines()
--------------------------------------------------
-Nestão seção serão apresentadas melhorias do Java 8 para encontrar e ler arquivos. São operações que já poderiam ser realizadas com outros métodos antes do Java 8. Porém, com essas melhorias, é possível realizar essas operações utilizando Streams.
+In this section Java 8 enhancements for finding and reading files will be presented. These are operations that could already be performed with other methods before Java 8. However, with these improvements, you can perform these operations using Streams.
-. É possível criar um _Stream_ para acessar todos os arquivos, diretórios e subdiretórios de um `Path`.
+. You can create a _Stream_ to access all files, directories and subdirectories of a `Path`.
+
[source,java,indent=0]
.{java-package}/fileimprovements/Improvements_Walk.java
@@ -20,36 +18,36 @@ Nestão seção serão apresentadas melhorias do Java 8 para encontrar e ler arq
include::{section-java-package}/fileimprovements/Improvements_Walk.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-
-Todos os arquivos e diretórios:
-/home/rinaldo/arquivos
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/subpasta1/subpasta12
-/home/rinaldo/arquivos/subpasta1/subpasta12/arquivo122.txt
-/home/rinaldo/arquivos/subpasta1/subpasta12/arquivo121.txt
-/home/rinaldo/arquivos/subpasta1/arquivo11.txt
-/home/rinaldo/arquivos/subpasta1/subpasta11
-/home/rinaldo/arquivos/subpasta1/arquivo12.txt
-/home/rinaldo/arquivos/subpasta1/arquivo13.txt
-/home/rinaldo/arquivos/arquivo2.txt
-
-Os primeiro 5 arquivos e diretórios:
-/home/rinaldo/arquivos
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/subpasta1/subpasta12
+Path: /home/rinaldo/files
+
+All files and directories:
+/home/rinaldo/files
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/subfolder1/subfolder12
+/home/rinaldo/files/subfolder1/subfolder12/file122.txt
+/home/rinaldo/files/subfolder1/subfolder12/file121.txt
+/home/rinaldo/files/subfolder1/file11.txt
+/home/rinaldo/files/subfolder1/subfolder11
+/home/rinaldo/files/subfolder1/file12.txt
+/home/rinaldo/files/subfolder1/file13.txt
+/home/rinaldo/files/file2.txt
+
+The first 5 files and directories:
+/home/rinaldo/files
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/subfolder1/subfolder12
----
+
-Perceba que a instância criada é realmente um `Stream`, de tal forma que é possível realizar as operações disponíveis em qualquer __Stream__, como o método `filter`.
+Note that the created instance is really a `Stream`, so that you can perform the operations available on any _Stream_, such as the `filter` method.
-. Existe uma versão do método `walk` para definir opções adicionais e limitar a profundidade do acesso aos subdiretórios.
+. There is a version of the `walk` method for setting additional options and limiting the depth of access to subdirectories.
+
[source,java,indent=0]
.{java-package}/fileimprovements/Improvements_WalkDepth.java
@@ -57,25 +55,25 @@ Perceba que a instância criada é realmente um `Stream`, de tal forma que
include::{section-java-package}/fileimprovements/Improvements_WalkDepth.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
+Path: /home/rinaldo/files
-Arquivos e Links simbólicos até o segundo nível:
-/home/rinaldo/arquivos
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/subpasta1/subpasta12
-/home/rinaldo/arquivos/subpasta1/arquivo11.txt
-/home/rinaldo/arquivos/subpasta1/subpasta11
-/home/rinaldo/arquivos/subpasta1/arquivo12.txt
-/home/rinaldo/arquivos/subpasta1/arquivo13.txt
-/home/rinaldo/arquivos/arquivo2.txt
+Symbolic files and links to the second level:
+/home/rinaldo/files
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/subfolder1/subfolder12
+/home/rinaldo/files/subfolder1/file11.txt
+/home/rinaldo/files/subfolder1/subfolder11
+/home/rinaldo/files/subfolder1/file12.txt
+/home/rinaldo/files/subfolder1/file13.txt
+/home/rinaldo/files/file2.txt
----
-. É possível pesquisar por um arquivo utilizando o método `find` e filtrar por atributos.
+. You can search for a file using the `find` method and filter by attributes.
+
[source,java,indent=0]
.{java-package}/fileimprovements/Improvements_Find.java
@@ -83,23 +81,23 @@ Arquivos e Links simbólicos até o segundo nível:
include::{section-java-package}/fileimprovements/Improvements_Find.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
+Path: /home/rinaldo/files
-Todos os arquivos, ignorando diretórios, até o segundo nível:
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1/arquivo11.txt
-/home/rinaldo/arquivos/subpasta1/arquivo12.txt
-/home/rinaldo/arquivos/subpasta1/arquivo13.txt
-/home/rinaldo/arquivos/arquivo2.txt
+All files, skipping directories, up to the second level:
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1/file11.txt
+/home/rinaldo/files/subfolder1/file12.txt
+/home/rinaldo/files/subfolder1/file13.txt
+/home/rinaldo/files/file2.txt
----
+
-Perceba que ao utilizar o `find` a expressão lambda tem acesso ao `Path` e seus atributos, que é uma instância de `BasicFileAttributes`, permitindo uma maior flexibilidade na busca.
+Note that by using `find` the lambda expression has access to `Path` and its attributes, which is an instance of `BasicFileAttributes`, allowing for greater flexibility in searching.
-. É possível listar o conteúdo de um `Path` utilizando o método `list`.
+. You can list the contents of a `Path` using the `list` method.
+
[source,java,indent=0]
.{java-package}/fileimprovements/Improvements_List.java
@@ -107,26 +105,26 @@ Perceba que ao utilizar o `find` a expressão lambda tem acesso ao `Path` e seus
include::{section-java-package}/fileimprovements/Improvements_List.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
+Path: /home/rinaldo/files
-Listagem do diretório:
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/subpasta1
-/home/rinaldo/arquivos/arquivo2.txt
+Directory listing:
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/subfolder1
+/home/rinaldo/files/file2.txt
-Listagem do diretório com filtro:
-/home/rinaldo/arquivos/arquivo1.txt
-/home/rinaldo/arquivos/arquivo3.txt
-/home/rinaldo/arquivos/arquivo2.txt
+Directory listing, files only:
+/home/rinaldo/files/file1.txt
+/home/rinaldo/files/file3.txt
+/home/rinaldo/files/file2.txt
----
+
-Perceba que o `list` não apresenta elementos dos subdiretórios.
+Note that `list` has no subdirectory elements.
-. É possível recuperar todas as linhas de um arquivo como um _Stream_ utilizando o método `lines`.
+. You can retrieve all lines of a file as a _Stream_ using the `lines` method.
+
[source,java,indent=0]
.{java-package}/fileimprovements/Improvements_Lines.java
@@ -134,33 +132,33 @@ Perceba que o `list` não apresenta elementos dos subdiretórios.
include::{section-java-package}/fileimprovements/Improvements_Lines.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos/subpasta1/arquivo11.txt
+Path: /home/rinaldo/files/subfolder1/file11.txt
-Conteúdo do arquivo:
+File content:
1
2
3
4
5
-Conteúdo do arquivo:
+File contents greater than 2:
3
4
5
----
-
+.References
****
* Presenting the New Stream Methods
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 486). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 486). Wiley. Kindle Edition.
* https://www.baeldung.com/java-list-directory-files[List Files in a Directory in Java.]
* https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html[Class Files.] Java Plataform SE 7.
-****
\ No newline at end of file
+****
diff --git a/book/07-file-io/sections/05-watch-service.asc b/book/07-file-io/sections/05-watch-service.asc
index f7aa76f..7048000 100644
--- a/book/07-file-io/sections/05-watch-service.asc
+++ b/book/07-file-io/sections/05-watch-service.asc
@@ -3,25 +3,23 @@
=== WatchService
-.Objetivo
+.Objective
--------------------------------------------------
Observe the changes in a directory by using the WatchService interface
--
-Observar as mudanças em um diretório a partir da utilização da Interface WatchService
--------------------------------------------------
-O WatchService é uma API para monitorar mudanças em arquivos e diretórios. Serão apresentadas as principais formas de realizar essa monitoração.
+WatchService is an API for monitoring file and directory changes. The main ways to carry out this monitoring will be presented.
-Para utilizar a API são necessárias 4 classes principais:
+To use the API you need 4 main classes:
-* WatchService -> representa o serviço em si de monitoração;
-* StandardWatchEventKinds -> representa os tipos de alteração que se deseja monitorar: criar, apagar ou modificar;
-* WatchKey -> representa um retorno do serviço informando que houveram alterações;
-* WatchEvent -> representa um evento em si, onde é possível obter informações do que foi alterado.
+* WatchService -> represents the monitoring service itself;
+* StandardWatchEventKinds -> represents the types of changes you want to monitor: create, delete or modify;
+* WatchKey -> represents a return of the service informing that there have been changes;
+* WatchEvent -> represents an event itself, where you can get information about what has changed.
-//-
+// -
-. É possível observar criações ou deleções de arquivos em um diretório.
+. You can observe file creations or deletions in a directory.
+
[source,java,indent=0]
.{java-package}/watchservice/WatchService_CreateDelete.java
@@ -29,32 +27,32 @@ Para utilizar a API são necessárias 4 classes principais:
include::{section-java-package}/watchservice/WatchService_CreateDelete.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Eventos capturados. Quantidade: 1
-Evento ocorrido. Tipo : ENTRY_DELETE. Contexto: arquivo1.txt
-Eventos capturados. Quantidade: 1
-Evento ocorrido. Tipo : ENTRY_CREATE. Contexto: arquivo1.txt
+Path: /home/rinaldo/files
+Events captured. Quantity: 1
+Event occurred. Type: ENTRY_DELETE. Context: file1.txt
+Events captured. Quantity: 1
+Event occurred. Type: ENTRY_CREATE. Context: file1.txt
----
+
-Isso é o que seria impresso no console caso o `arquivo1.txt` fosse apagado e depois criado novamente.
+This is what would be printed on the console if `file1.txt` were deleted and then created again.
+
-Perceba os passos que foram feitos:
+Note the steps that were taken:
+
-.. Um WatchService foi criado
-.. O service foi registrado no `Path` com os eventos desejados
-.. Foi criado um _loop_ infinito para realizar a monitoração de forma contínua
-.. Foi chamado o método `take`, que aguarda até haver eventos e assim, retorná-los
-.. Foi chamado o método `pollEvents` para recuperar os eventos que ocorreram
-.. Os eventos foram impressos no console
-.. O `WatchKey` foi resetado para que pudesse ser utilizado novamente
+.. A WatchService has been created.
+.. The service has been registered in `Path` with the desired events.
+.. An infinite _loop_ has been created to continuously monitor.
+.. The `take` method was called, which waits until there are events and thus returns them.
+.. The `pollEvents` method was called to retrieve events that occurred.
+.. Events were printed on console.
+.. WatchKey has been reset so that it can be used again.
+
-Esse é o básico de um `WatchService`. Perceba que ele é um recurso que deve ser fechado, por isso está na sintaxe de `try-with-resources`.
+This is the basics of a `WatchService`. Note that it is a resource that must be closed, so it is in the `try-with-resources` syntax.
-. É possível monitorar mudanças em arquivos de um diretório.
+. You can monitor changes to files in a directory.
+
[source,java,indent=0]
.{java-package}/watchservice/WatchService_Modify.java
@@ -62,21 +60,21 @@ Esse é o básico de um `WatchService`. Perceba que ele é um recurso que deve s
include::{section-java-package}/watchservice/WatchService_Modify.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Eventos capturados. Quantidade: 1
-Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: .arquivo1.txt.kate-swp
-Eventos capturados. Quantidade: 1
-Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: arquivo1.txt.h26197
-Eventos capturados. Quantidade: 1
-Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: arquivo1.txt.h26197
+Path: /home/rinaldo/files
+Events captured. Quantity: 1
+Event occurred. Type: ENTRY_MODIFY. Context: .file1.txt.kate-swp
+Events captured. Quantity: 1
+Event occurred. Type: ENTRY_MODIFY. Context: file1.txt.h26197
+Events captured. Quantity: 1
+Event occurred. Type: ENTRY_MODIFY. Context: file1.txt.h26197
----
+
-Esses foram os eventos que ocorreram ao abrir o `arquivo1.txt` com o editor `Kate`, acrescentar um caracter, e salvar o arquivo.
+These were the events that occurred when opening `file1.txt` with the `Kate` editor, adding a character, and saving the file.
-. Não é possível monitorar diretamente um arquivo.
+. Unable to monitor a file directly.
+
[source,java,indent=0]
.{java-package}/watchservice/WatchService_File.java
@@ -84,20 +82,20 @@ Esses foram os eventos que ocorreram ao abrir o `arquivo1.txt` com o editor `Kat
include::{section-java-package}/watchservice/WatchService_File.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos/arquivo1.txt
-java.nio.file.NotDirectoryException: /home/rinaldo/arquivos/arquivo1.txt
+Path: /home/rinaldo/files/file1.txt
+java.nio.file.NotDirectoryException: /home/rinaldo/files/file1.txt
at sun.nio.fs.LinuxWatchService$Poller.implRegister(LinuxWatchService.java:249)
at sun.nio.fs.AbstractPoller.processRequests(AbstractPoller.java:260)
at sun.nio.fs.LinuxWatchService$Poller.run(LinuxWatchService.java:364)
at java.lang.Thread.run(Thread.java:748)
----
+
-Perceba que ocorre exceção ao tentar monitorar diretamente o `arquivo1.txt`.
+Note that exception occurs when trying to directly monitor `file1.txt`.
-. É possível recuperar um `WatchKey` imediatamente ou aguardar um período específico com os métodos `poll`.
+. You can retrieve a `WatchKey` immediately or wait for a specific period with `poll` methods.
+
[source,java,indent=0]
.{java-package}/watchservice/WatchService_Poll.java
@@ -105,27 +103,29 @@ Perceba que ocorre exceção ao tentar monitorar diretamente o `arquivo1.txt`.
include::{section-java-package}/watchservice/WatchService_Poll.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Path: /home/rinaldo/arquivos
-Horário antes do poll sem timeout: 14:55:10.298
-WatchKey do poll: null
-Horário depois do poll sem timeout: 14:55:10.298
-Horário antes do poll com timeout: 14:55:10.298
-WatchKey do poll com timeout: null
-Horário depois do poll com timeout: 14:55:15.300
+Path: /home/rinaldo/files
+Time before poll without timeout: 14:55:10.298
+WatchKey's poll: null
+Time after poll without timeout: 14:55:10.298
+Time before poll with timeout: 14:55:10.298
+WatchKey's poll with timeout: null
+Time after poll with timeout: 14:55:15.300
----
+
-Perceba que o primeiro `poll` retorna imediatamente, mesmo que nenhum evento tenha ocorrido. Já o segundo aguarda por 5 segundos para retornar, mesmo que não haja evento.
+Note that the first `poll` returns immediately, even if no events have occurred. The second waits for 5 seconds to return, even if there is no event.
+
-Nos cenários de monitoração, o ideal é utilizar o `take`, caso contrário seria necessário invocar o `poll` inúmeras vezes, enquanto o `take` apenas aguarda indefinidamente até que haja um evento.
+In monitoring scenarios, it is best to use take, otherwise you would need to invoke poll countless times, while take only waits indefinitely until there is an event.
+
+.References
****
* Monitoring a Directory for Changes
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 625). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 625). Wiley. Kindle Edition.
* https://www.baeldung.com/java-nio2-watchservice[A Guide to WatchService in Java NIO2.]
@@ -133,4 +133,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/tutorial/essential/io/notification.html[Watching a Directory for Changes.] The Java™ Tutorials.
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/01-diamond.asc b/book/08-java-collections/sections/01-diamond.asc
index 0e08315..1fda400 100644
--- a/book/08-java-collections/sections/01-diamond.asc
+++ b/book/08-java-collections/sections/01-diamond.asc
@@ -1,16 +1,14 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Diamond Operator (Operador Diamante)
+=== Diamond Operator
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses diamond with generic declarations
--
-Desenvolver código que usa o diamond (diamante) com declarações de generics
--------------------------------------------------
-O Diamond Operator (ou Operador Diamante) foi criado no Java 7 para remover código desnecessário ao declarar classes que usam `Generics` (ou tipos genéricos). Abaixo um exemplo que é possível omitir o tipo de algumas classes utilizando o _Diamond Operator_.
+Diamond Operator was created in Java 7 to remove unnecessary code when declaring classes that use `Generics` (or generic types). Below is an example that you can omit the type of some classes using _Diamond Operator_.
[source,java,indent=0]
.{java-package}/diamond/Collections_Diamond.java
@@ -18,12 +16,13 @@ O Diamond Operator (ou Operador Diamante) foi criado no Java 7 para remover cód
include::{section-java-package}/diamond/Collections_Diamond.java[tag=code]
----
+.References
****
* Using the Diamond Operator
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 596). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 596). Wiley. Kindle Edition.
* https://www.baeldung.com/java-diamond-operator[Guide to the Diamond Operator in Java.]
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/02-collections-lambda.asc b/book/08-java-collections/sections/02-collections-lambda.asc
index 71dfbb7..9eb1200 100644
--- a/book/08-java-collections/sections/02-collections-lambda.asc
+++ b/book/08-java-collections/sections/02-collections-lambda.asc
@@ -1,16 +1,14 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Collections e lambda
+=== Collections and lambda
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that iterates a collection, filters a collection, and sorts a collection by using lambda expressions
--
-Desenvolver código que itera uma coleção, filtra uma coleção, e classifica em ordem uma coleção utilizando expressões lambda
--------------------------------------------------
-. É possível iterar diretamente sobre uma coleção utilizando forEach.
+. You can iterate directly over a collection using forEach.
+
[source,java,indent=0]
.{java-package}/lambda/CollectionsLambda_ForEach.java
@@ -18,7 +16,7 @@ Desenvolver código que itera uma coleção, filtra uma coleção, e classifica
include::{section-java-package}/lambda/CollectionsLambda_ForEach.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
1
@@ -28,7 +26,7 @@ include::{section-java-package}/lambda/CollectionsLambda_ForEach.java[tag=code]
9
----
-. É possível filtrar a coleção.
+. You can filter the collection.
+
[source,java,indent=0]
.{java-package}/lambda/CollectionsLambda_Filter.java
@@ -36,7 +34,7 @@ include::{section-java-package}/lambda/CollectionsLambda_ForEach.java[tag=code]
include::{section-java-package}/lambda/CollectionsLambda_Filter.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
6
@@ -44,7 +42,7 @@ include::{section-java-package}/lambda/CollectionsLambda_Filter.java[tag=code]
9
----
-. É possível classificar em ordem a coleção.
+. You can sort the collection in order.
+
[source,java,indent=0]
.{java-package}/lambda/CollectionsLambda_Sort.java
@@ -52,7 +50,7 @@ include::{section-java-package}/lambda/CollectionsLambda_Filter.java[tag=code]
include::{section-java-package}/lambda/CollectionsLambda_Sort.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
1
@@ -62,7 +60,7 @@ include::{section-java-package}/lambda/CollectionsLambda_Sort.java[tag=code]
9
----
-. É possível combinar as operações.
+. It is possible to combine the operations.
+
[source,java,indent=0]
.{java-package}/lambda/CollectionsLambda_Combined.java
@@ -70,7 +68,7 @@ include::{section-java-package}/lambda/CollectionsLambda_Sort.java[tag=code]
include::{section-java-package}/lambda/CollectionsLambda_Combined.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
26
@@ -79,12 +77,13 @@ include::{section-java-package}/lambda/CollectionsLambda_Combined.java[tag=code]
54
----
+.References
****
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/03-data-search.asc b/book/08-java-collections/sections/03-data-search.asc
index 081c6d4..00d2393 100644
--- a/book/08-java-collections/sections/03-data-search.asc
+++ b/book/08-java-collections/sections/03-data-search.asc
@@ -1,16 +1,14 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Buscar por dados
+=== Search for data
-.Objetivo
+.Objective
--------------------------------------------------
Search for data by using methods, such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()
--
-Buscar por dados utilizando métodos, como findFirst(), findAny(), anyMatch(), allMatch(), e noneMatch()
--------------------------------------------------
-. É possível recuperar o primeiro ou um elemento qualquer da coleção.
+. You can retrieve the first or any element from the collection.
+
[source,java,indent=0]
.{java-package}/datasearch/DataSearch_FindFirstAny.java
@@ -18,14 +16,14 @@ Buscar por dados utilizando métodos, como findFirst(), findAny(), anyMatch(), a
include::{section-java-package}/datasearch/DataSearch_FindFirstAny.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
First: 1
Any: 9
----
-. É possível verificar se os elementos da coleção atendem ou não a algum critério.
+. You can check whether or not collection elements meet any criteria.
+
[source,java,indent=0]
.{java-package}/datasearch/DataSearch_Match.java
@@ -33,7 +31,7 @@ Any: 9
include::{section-java-package}/datasearch/DataSearch_Match.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
anyMatch: true
@@ -41,12 +39,13 @@ allMatch: false
noneMatch: false
----
+.References
****
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/04-calculations.asc b/book/08-java-collections/sections/04-calculations.asc
index 3c4d320..f1d48f7 100644
--- a/book/08-java-collections/sections/04-calculations.asc
+++ b/book/08-java-collections/sections/04-calculations.asc
@@ -1,16 +1,14 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Fazendo cálculos e coletando resultados de Streams
+=== Perform Calculations and Collecting Streams Results
-.Objetivo
+.Objective
--------------------------------------------------
Perform calculations on Java Streams by using count, max, min, average, and sum methods and save results to a collection by using the collect method and Collector class, including the averagingDouble, groupingBy, joining, partitioningBy methods
--
-Realizar cálculos em Streams usando os métodos count, max, min, average, e sum e salvar resultados em uma coleção usando o método collect e a classe Collector, incluindo os métodos averagingDouble, groupingBy, joining, partitioningBy
--------------------------------------------------
-. É possível pegar o maior ou menor valor, ou a quantidade de elementos da coleção.
+. You can get the largest or smallest value, or the number of elements in the collection.
+
[source,java,indent=0]
.{java-package}/calculations/Collections_MaxMinCount.java
@@ -18,7 +16,7 @@ Realizar cálculos em Streams usando os métodos count, max, min, average, e sum
include::{section-java-package}/calculations/Collections_MaxMinCount.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Max: 9
@@ -26,7 +24,7 @@ Min: 1
Count: 9
----
-. É possível pegar a média dos valores da coleção.
+. You can take the average of the collection values.
+
[source,java,indent=0]
.{java-package}/calculations/Collections_AveragingDouble.java
@@ -34,13 +32,13 @@ Count: 9
include::{section-java-package}/calculations/Collections_AveragingDouble.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
Média: 5.0
----
-. É possível agrupar os valores da coleção por uma regra específica.
+. You can group collection values by a specific rule.
+
[source,java,indent=0]
.{java-package}/calculations/Collections_GroupingBy.java
@@ -48,13 +46,13 @@ Média: 5.0
include::{section-java-package}/calculations/Collections_GroupingBy.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Mapa de resto da divisão por 3: {0=[3, 6, 9], 1=[1, 4, 7], 2=[2, 5, 8]}
+Map of rest of division by 3: {0=[3, 6, 9], 1=[1, 4, 7], 2=[2, 5, 8]}
----
-. É possível concatenar os valores da coleção.
+. You can concatenate the collection values.
+
[source,java,indent=0]
.{java-package}/calculations/Collections_Joining.java
@@ -62,13 +60,13 @@ Mapa de resto da divisão por 3: {0=[3, 6, 9], 1=[1, 4, 7], 2=[2, 5, 8]}
include::{section-java-package}/calculations/Collections_Joining.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Junção dos valores como String: 123456789
+Join values as String: 123456789
----
-. É possível separar os valores da coleção em um mapa com chaves `true` e `false`, de acordo com uma função lambda.
+. You can separate collection values in a map with `true` and `false` keys, according to a lambda function.
+
[source,java,indent=0]
.{java-package}/calculations/Collections_PartitioningBy.java
@@ -76,18 +74,19 @@ Junção dos valores como String: 123456789
include::{section-java-package}/calculations/Collections_PartitioningBy.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Mapa de pares e ímpares: {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8]}
+Even and odd map: {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8]}
----
+.References
****
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/05-collection-improvements.asc b/book/08-java-collections/sections/05-collection-improvements.asc
index b780203..1c4d9ce 100644
--- a/book/08-java-collections/sections/05-collection-improvements.asc
+++ b/book/08-java-collections/sections/05-collection-improvements.asc
@@ -1,18 +1,16 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Melhorias de Java 8 em Coleções
+=== Java 8 collection improvements
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses Java SE 8 collection improvements, including the Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods
--
-Desenvolver código que use as melhorias em coleções do Java SE 8, incluindo os métodos Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), e Map.computeIfPresent()
--------------------------------------------------
-O Java 8 trouxe vários métodos em Collections que utilizam como argumento uma função lambda, facilitando algumas operações. Serão apresentados exemplos dos 4 métodos relacionados a esse objetivo.
+Java 8 has introduced several methods in Collections that use a lambda function as argument, making some operations easier. Examples of the 4 methods related to this objective will be presented.
-. É possível remover um item de uma coleção condicionalmente com uma função lambda.
+. You can conditionally remove an item from a collection with a lambda function.
+
[source,java,indent=0]
.{java-package}/improvements/Collections_RemoveIf.java
@@ -20,14 +18,14 @@ O Java 8 trouxe vários métodos em Collections que utilizam como argumento uma
include::{section-java-package}/improvements/Collections_RemoveIf.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Lista antes do removeIf: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-Lista depois do removeIf: [1, 3, 5, 7, 9]
+List before removeIf: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+List after removeIf: [1, 3, 5, 7, 9]
----
-. É possível modificar todos os elementos da coleção de acordo com uma operação lambda.
+. You can modify all elements of the collection according to a lambda operation.
+
[source,java,indent=0]
.{java-package}/improvements/Collections_ReplaceAll.java
@@ -35,14 +33,14 @@ Lista depois do removeIf: [1, 3, 5, 7, 9]
include::{section-java-package}/improvements/Collections_ReplaceAll.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Lista antes do replaceAll: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-Lista depois do replaceAll: [2, 4, 6, 8, 10, 12, 14, 16, 18]
+List before replaceAll: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+List after replaceAll: [2, 4, 6, 8, 10, 12, 14, 16, 18]
----
-. É possível colocar valores em um `Map` a partir de uma função lambda, apenas se a chave *não* estiver presente no `Map`.
+. You can put values in a `Map` from a lambda function only if the *key* is not present in `Map`.
+
[source,java,indent=0]
.{java-package}/improvements/Collections_ComputeIfAbsent.java
@@ -50,14 +48,14 @@ Lista depois do replaceAll: [2, 4, 6, 8, 10, 12, 14, 16, 18]
include::{section-java-package}/improvements/Collections_ComputeIfAbsent.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Map antes do computeIfAbsent: {A=65, B=66}
-Map depois do computeIfAbsent: {A=65, B=66, C=67}
+Map before computeIfAbsent: {A=65, B=66}
+Map after computeIfAbsent: {A=65, B=66, C=67}
----
-. É possível alterar valores em um `Map` a partir de uma função lambda, apenas se a chave estiver presente no `Map`.
+. You can change values in a `Map` from a lambda function only if the key is present in `Map`.
+
[source,java,indent=0]
.{java-package}/improvements/Collections_ComputeIfPresent.java
@@ -65,19 +63,20 @@ Map depois do computeIfAbsent: {A=65, B=66, C=67}
include::{section-java-package}/improvements/Collections_ComputeIfPresent.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Map antes do computeIfPresent: {A=65, B=66}
-Map depois do computeIfPresent: {A=4225, B=4356}
+Map before computeIfPresent: {A=65, B=66}
+Map after computeIfPresent: {A=4225, B=4356}
----
+.References
****
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
-****
\ No newline at end of file
+****
diff --git a/book/08-java-collections/sections/06-merge-map.asc b/book/08-java-collections/sections/06-merge-map.asc
index 18f89ed..8b13ed7 100644
--- a/book/08-java-collections/sections/06-merge-map.asc
+++ b/book/08-java-collections/sections/06-merge-map.asc
@@ -1,18 +1,16 @@
:java-package: src/org/j6toj8/collections
:section-java-package: ../../../{java-package}
-=== Maps e Streams
+=== Maps and Streams
-.Objetivo
+.Objective
--------------------------------------------------
Develop code that uses the merge(), flatMap(), and map() methods on Java Streams
--
-Desenvolver código que usa os métodos merge(), flatMap(), e map() em Streams Java.
--------------------------------------------------
-Dos objetivos desta seção, apenas o método `merge` ainda não foi apresentado em outras seções.
+About the objectives of this section, only the `merge` method has not yet been introduced in other sections.
-. É possível colocar um novo valor em um mapa, ou alterar o valor que já estava presente, utilizando o método `merge`.
+. You can put a new value on a map, or change the value that was already present using the `merge` method.
+
[source,java,indent=0]
.{java-package}/mergemap/Collections_Merge.java
@@ -20,16 +18,16 @@ Dos objetivos desta seção, apenas o método `merge` ainda não foi apresentado
include::{section-java-package}/mergemap/Collections_Merge.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
-Map antes do merge: {1=String1-, 2=String2-}
-Map depois do merge: {1=String1-StringA, 2=String2-StringB, 3=StringC, 4=StringD}
+Map before merge: {1=String1-, 2=String2-}
+Map after merge: {1=String1-StringA, 2=String2-StringB, 3=StringC, 4=StringD}
----
+
-Perceba que, para as chaves que já estavam presentes no `Map`, foi aplicada a função lambda. Para as chaves que ainda não estavam presentes, foi apenas inserida a `String` passada como valor.
+Note that for keys that were already present in `Map`, the lambda function was applied. For keys that were not already present, only the `String` passed as value was entered.
-. É possível transformar valores em uma coleção com o método `map`.
+. You can transform values into a collection with the `map` method.
+
[source,java,indent=0]
.{java-package}/mergemap/Collections_Map.java
@@ -37,7 +35,7 @@ Perceba que, para as chaves que já estavam presentes no `Map`, foi aplicada a f
include::{section-java-package}/mergemap/Collections_Map.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
2
@@ -51,7 +49,7 @@ include::{section-java-package}/mergemap/Collections_Map.java[tag=code]
18
----
-. É possível percorrer outro Stream, em sequência com o Stream atual, utilizando o método `flatMap`.
+. You can traverse another Stream in sequence with the current Stream using the `flatMap` method.
+
[source,java,indent=0]
.{java-package}/mergemap/Collections_FlatMap.java
@@ -59,13 +57,13 @@ include::{section-java-package}/mergemap/Collections_Map.java[tag=code]
include::{section-java-package}/mergemap/Collections_FlatMap.java[tag=code]
----
+
-.Saída no console
+.console output
[source,console]
----
- Com map:
-java.util.stream.ReferencePipeline$Head@e9e54c2
+ With map:
+java.util.stream.ReferencePipeline$Head@5f184fc6
- Com flatMap:
+ With flatMap:
M
a
n
@@ -74,20 +72,21 @@ e
l
----
+
-Perceba que uma transformação que resulta em outro Stream é percorrida como se fosse o próprio Stream original.
+Note that a transformation that results in another Stream is traversed as if it were the original Stream itself.
+.References
****
* Additions in Java 8
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 152). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 152). Wiley. Kindle Edition.
* Using Streams
+
-Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Edição do Kindle.
+Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 185). Wiley. Kindle Edition.
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
* https://www.baeldung.com/java-merge-maps[Merging Two Maps with Java 8.]
-****
\ No newline at end of file
+****
diff --git a/ch08-java-collections.asc b/ch08-java-collections.asc
index 84a4ec1..b1cb371 100644
--- a/ch08-java-collections.asc
+++ b/ch08-java-collections.asc
@@ -1,7 +1,7 @@
[[ch08-java-collections]]
== Java Collections
-As seções de *Expressões Lambda* e *Streams* já possuem bastante conteúdo sobre os tópicos dos objetivos deste capítulo, e as explicações em detalhes podem ser encontradas lá. Aqui serão apresentados apenas exemplos adicionais especificamente em coleções (__Collections__), pois alguns exemplos das outras seções utilizam outros tipos de __Streams__.
+The *Lambda Expressions* and *Streams* sections already contain plenty of content about the objectives of this chapter, and the detailed explanations can be found there. Here we will present only additional examples specifically in collections (_Collections_), as some examples from the other sections use other types of _Streams_.
include::book/08-java-collections/sections/01-diamond.asc[]
include::book/08-java-collections/sections/02-collections-lambda.asc[]
diff --git a/resources/Text_es_ES.properties b/resources/Text_es_ES.properties
index 6117fa0..d5fb8b9 100644
--- a/resources/Text_es_ES.properties
+++ b/resources/Text_es_ES.properties
@@ -1,2 +1,2 @@
-!arquivo do locale es_ES
+!locale es_ES file
glass=\tvaso
\ No newline at end of file
diff --git a/resources/Text_pt_BR.properties b/resources/Text_pt_BR.properties
index d1cf4b1..5461ed9 100644
--- a/resources/Text_pt_BR.properties
+++ b/resources/Text_pt_BR.properties
@@ -1,2 +1,2 @@
-#arquivo do locale pt_BR
+#locale pt_BR file
pen=caneta
\ No newline at end of file
diff --git a/src/org/j6toj8/collections/calculations/Collections_GroupingBy.java b/src/org/j6toj8/collections/calculations/Collections_GroupingBy.java
index b1ea9c8..b2d45b0 100644
--- a/src/org/j6toj8/collections/calculations/Collections_GroupingBy.java
+++ b/src/org/j6toj8/collections/calculations/Collections_GroupingBy.java
@@ -11,10 +11,10 @@ public static void main(String[] args) {
// tag::code[]
List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
- Map> mapaDivisaoPor3 = list.stream()
+ Map> mapDivisionBy3 = list.stream()
.collect(Collectors.groupingBy(n -> n % 3));
- System.out.println("Mapa de resto da divisão por 3: " + mapaDivisaoPor3);
+ System.out.println("Map of rest of division by 3: " + mapDivisionBy3);
// end::code[]
}
}
diff --git a/src/org/j6toj8/collections/calculations/Collections_Joining.java b/src/org/j6toj8/collections/calculations/Collections_Joining.java
index c9b8c0c..f7f925d 100644
--- a/src/org/j6toj8/collections/calculations/Collections_Joining.java
+++ b/src/org/j6toj8/collections/calculations/Collections_Joining.java
@@ -10,11 +10,11 @@ public static void main(String[] args) {
// tag::code[]
List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
- String juncao = list.stream()
+ String join = list.stream()
.map(n -> n.toString())
.collect(Collectors.joining());
- System.out.println("Junção dos valores como String: " + juncao);
+ System.out.println("Join values as String: " + join);
// end::code[]
}
}
diff --git a/src/org/j6toj8/collections/calculations/Collections_MaxMinCount.java b/src/org/j6toj8/collections/calculations/Collections_MaxMinCount.java
index 42607c9..a6b1668 100644
--- a/src/org/j6toj8/collections/calculations/Collections_MaxMinCount.java
+++ b/src/org/j6toj8/collections/calculations/Collections_MaxMinCount.java
@@ -11,17 +11,17 @@ public static void main(String[] args) {
List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
OptionalInt max = list.stream()
- .mapToInt(Integer::intValue) // transforma para int
+ .mapToInt(Integer::intValue) // transform to int
.max();
System.out.println("Max: " + max.getAsInt());
OptionalInt min = list.stream()
- .mapToInt(Integer::intValue) // transforma para int
+ .mapToInt(Integer::intValue) // transform to int
.min();
System.out.println("Min: " + min.getAsInt());
long count = list.stream()
- .mapToInt(Integer::intValue) // transforma para int
+ .mapToInt(Integer::intValue) // transform to int
.count();
System.out.println("Count: " + count);
// end::code[]
diff --git a/src/org/j6toj8/collections/calculations/Collections_PartitioningBy.java b/src/org/j6toj8/collections/calculations/Collections_PartitioningBy.java
index 689f49f..7951965 100644
--- a/src/org/j6toj8/collections/calculations/Collections_PartitioningBy.java
+++ b/src/org/j6toj8/collections/calculations/Collections_PartitioningBy.java
@@ -11,10 +11,10 @@ public static void main(String[] args) {
// tag::code[]
List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
- Map> mapaParImpar = list.stream()
+ Map> mapEvenOdd = list.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
- System.out.println("Mapa de pares e ímpares: " + mapaParImpar);
+ System.out.println("Even and odd map: " + mapEvenOdd);
// end::code[]
}
}
diff --git a/src/org/j6toj8/collections/diamond/Collections_Diamond.java b/src/org/j6toj8/collections/diamond/Collections_Diamond.java
index e93a3f7..0a33dac 100644
--- a/src/org/j6toj8/collections/diamond/Collections_Diamond.java
+++ b/src/org/j6toj8/collections/diamond/Collections_Diamond.java
@@ -9,22 +9,22 @@ public class Collections_Diamond {
public static void main(String[] args) {
// tag::code[]
- List l1 = new ArrayList(); // sem diamond
- List l2 = new ArrayList<>(); // com diamond
- List<> l3 = new ArrayList(); // NÃO COMPILA - diamond só pode ser utilizado do lado direito
+ List l1 = new ArrayList(); // without diamond
+ List l2 = new ArrayList<>(); // with diamond
+ List<> l3 = new ArrayList(); // NOT COMPILING - diamond can only be used on the right side
- Map m1 = new HashMap(); // sem diamond
- Map m2 = new HashMap<>(); // com diamond
- Map<> m3 = new HashMap(); // NÃO COMPILA - diamond só do lado direito
+ Map m1 = new HashMap(); // without diamond
+ Map m2 = new HashMap<>(); // with diamond
+ Map<> m3 = new HashMap(); // NOT COMPILING - diamond can only be used on the right side
- Map, List> m4 = new HashMap, List>(); // sem diamond
- Map, List> m5 = new HashMap<>(); // com diamond
- Map, List> m6 = new HashMap<<>,<>>(); // NÃO COMPILA - a única sintaxe válida é <>
- Map, List> m7 = new HashMap, <>>(); // NÃO COMPILA - a única sintaxe válida é <>
+ Map, List> m4 = new HashMap, List>(); // without diamond
+ Map, List> m5 = new HashMap<>(); // with diamond
+ Map, List> m6 = new HashMap<<>,<>>(); // NOT COMPILING - the only valid syntax is <>
+ Map, List> m7 = new HashMap, <>>(); // NOT COMPILING - the only valid syntax is <>
- Map