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, List>, Map, List>> m8 = new HashMap<>(); // com diamond + Map, List>, Map, List>> m8 = new HashMap<>(); // with diamond - Map<> m9 = new HashMap<>(); // NÃO COMPILA - é necessário informar o tipo do lado esquerdo + Map<> m9 = new HashMap<>(); // NOT COMPILING - it's necessary to inform the type on the left side // end::code[] } diff --git a/src/org/j6toj8/collections/improvements/Collections_ComputeIfAbsent.java b/src/org/j6toj8/collections/improvements/Collections_ComputeIfAbsent.java index 3db5293..ddfc070 100644 --- a/src/org/j6toj8/collections/improvements/Collections_ComputeIfAbsent.java +++ b/src/org/j6toj8/collections/improvements/Collections_ComputeIfAbsent.java @@ -10,10 +10,10 @@ public static void main(String[] args) { map.put("A", "A".hashCode()); map.put("B", "B".hashCode()); - System.out.println("Map antes do computeIfAbsent: " + map); + System.out.println("Map before computeIfAbsent: " + map); map.computeIfAbsent("A", k -> k.hashCode()); map.computeIfAbsent("C", k -> k.hashCode()); - System.out.println("Map depois do computeIfAbsent: " + map); + System.out.println("Map after computeIfAbsent: " + map); // end::code[] } } diff --git a/src/org/j6toj8/collections/improvements/Collections_ComputeIfPresent.java b/src/org/j6toj8/collections/improvements/Collections_ComputeIfPresent.java index 8a4814b..84eb836 100644 --- a/src/org/j6toj8/collections/improvements/Collections_ComputeIfPresent.java +++ b/src/org/j6toj8/collections/improvements/Collections_ComputeIfPresent.java @@ -10,12 +10,12 @@ public static void main(String[] args) { map.put("A", "A".hashCode()); map.put("B", "B".hashCode()); - System.out.println("Map antes do computeIfPresent: " + map); - // k = chave; v = valor + System.out.println("Map before computeIfPresent: " + map); + // k = key; v = value map.computeIfPresent("A", (k, v) -> k.hashCode() * v); map.computeIfPresent("B", (k, v) -> k.hashCode() * v); map.computeIfPresent("C", (k, v) -> k.hashCode() * v); - System.out.println("Map depois do computeIfPresent: " + map); + System.out.println("Map after computeIfPresent: " + map); // end::code[] } } diff --git a/src/org/j6toj8/collections/improvements/Collections_RemoveIf.java b/src/org/j6toj8/collections/improvements/Collections_RemoveIf.java index 0f98b60..9707e44 100644 --- a/src/org/j6toj8/collections/improvements/Collections_RemoveIf.java +++ b/src/org/j6toj8/collections/improvements/Collections_RemoveIf.java @@ -10,9 +10,9 @@ public static void main(String[] args) { // tag::code[] List list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9)); - System.out.println("Lista antes do removeIf: " + list); - list.removeIf(n -> n % 2 == 0); // remove números pares - System.out.println("Lista depois do removeIf: " + list); + System.out.println("List before removeIf: " + list); + list.removeIf(n -> n % 2 == 0); // remove even numbers + System.out.println("List after removeIf: " + list); // end::code[] } } diff --git a/src/org/j6toj8/collections/improvements/Collections_ReplaceAll.java b/src/org/j6toj8/collections/improvements/Collections_ReplaceAll.java index 92fbf18..bbfad9b 100644 --- a/src/org/j6toj8/collections/improvements/Collections_ReplaceAll.java +++ b/src/org/j6toj8/collections/improvements/Collections_ReplaceAll.java @@ -10,9 +10,9 @@ public static void main(String[] args) { // tag::code[] List list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9)); - System.out.println("Lista antes do replaceAll: " + list); - list.replaceAll(n -> n * 2); // multiplica todos os elementos por 2 - System.out.println("Lista depois do replaceAll: " + list); + System.out.println("List before replaceAll: " + list); + list.replaceAll(n -> n * 2); // multiply all elements by 2 + System.out.println("List after replaceAll: " + list); // end::code[] } } diff --git a/src/org/j6toj8/collections/mergemap/Collections_FlatMap.java b/src/org/j6toj8/collections/mergemap/Collections_FlatMap.java index 421bbf2..39b4aaa 100644 --- a/src/org/j6toj8/collections/mergemap/Collections_FlatMap.java +++ b/src/org/j6toj8/collections/mergemap/Collections_FlatMap.java @@ -9,16 +9,14 @@ public static void main(String[] args) { // tag::code[] List list = Arrays.asList("Manoel"); - System.out.println("\n Com map: "); - // com map - as letras da String viram - // um Stream dentro de outro Stream + System.out.println("\n With map: "); + // com map - String letters become Stream within Stream list.stream() .map(s -> Arrays.stream(s.split(""))) .forEach(System.out::println); - System.out.println("\n Com flatMap: "); - // com flatMap - as letras da String viram dados - // do próprio Stream + System.out.println("\n With flatMap: "); + // with flatMap - String letters become data of the Stream list.stream() .flatMap(s -> Arrays.stream(s.split(""))) .forEach(System.out::println); diff --git a/src/org/j6toj8/collections/mergemap/Collections_Merge.java b/src/org/j6toj8/collections/mergemap/Collections_Merge.java index 05e0b30..55ab4ab 100644 --- a/src/org/j6toj8/collections/mergemap/Collections_Merge.java +++ b/src/org/j6toj8/collections/mergemap/Collections_Merge.java @@ -10,12 +10,12 @@ public static void main(String[] args) { map.put(1, "String1-"); map.put(2, "String2-"); - System.out.println("Map antes do merge: " + map); + System.out.println("Map before merge: " + map); map.merge(1, "StringA", (v1, v2) -> v1.concat(v2)); map.merge(2, "StringB", (v1, v2) -> v1.concat(v2)); map.merge(3, "StringC", (v1, v2) -> v1.concat(v2)); map.merge(4, "StringD", (v1, v2) -> v1.concat(v2)); - System.out.println("Map depois do merge: " + map); + System.out.println("Map after merge: " + map); // end::code[] } } diff --git a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java index c260295..62cd3f7 100644 --- a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java +++ b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java @@ -9,13 +9,13 @@ public class Concurrency_CollectionsSyncronized { public static void main(String[] args) { // tag::code[] - // Concurrent Map, garante o acesso de múltiplas threads + // Concurrent Map, ensures multi-threaded access Map concurrentHashMap = new ConcurrentHashMap<>(); - // Map Comum, NÃO garante o acesso de múltiplas threads + // Common Map, DOES NOT ensures multi-threaded access Map map = new HashMap<>(); - // Syncronized Map, garante o acesso de múltiplas threads + // Syncronized Map, ensures multi-threaded access Map synchronizedMap = Collections.synchronizedMap(map); // end::code[] } diff --git a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java index 4bfc98e..c4bedb9 100644 --- a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java +++ b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java @@ -19,7 +19,7 @@ public static void main(String[] args) { } } - System.out.println("Lista final: " + list); + System.out.println("Final list: " + list); // end::code[] } diff --git a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CyclicBarrier.java b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CyclicBarrier.java index ab51162..3da182a 100644 --- a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CyclicBarrier.java +++ b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CyclicBarrier.java @@ -6,47 +6,47 @@ public class Concurrency_CyclicBarrier { // tag::code[] - // Classe que será executada por 3 threads - static class Acao implements Runnable { + // Class that will be executed by 3 threads + static class Action implements Runnable { CyclicBarrier cyclicBarrier; - public Acao(CyclicBarrier cyclicBarrier) { + public Action(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { - System.out.println(Thread.currentThread().getName() + ": Primeira Parte"); + System.out.println(Thread.currentThread().getName() + ": First Part"); try { - cyclicBarrier.await(); // sincronização das threads + cyclicBarrier.await(); // thread synchronization } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } - System.out.println(Thread.currentThread().getName() + ": Segunda Parte"); + System.out.println(Thread.currentThread().getName() + ": Second Part"); try { - cyclicBarrier.await(); // sincronização das threads + cyclicBarrier.await(); // thread synchronization } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } - System.out.println(Thread.currentThread().getName() + ": Terceira Parte"); + System.out.println(Thread.currentThread().getName() + ": Third Part"); } } public static void main(String[] args) { - // Criação de um CyclicBarrier para 3 threads + // Creating a CyclicBarrier for 3 threads CyclicBarrier cyclicBarrier = new CyclicBarrier(3); - // Criação das threads - Thread thread1 = new Thread(new Acao(cyclicBarrier)); - Thread thread2 = new Thread(new Acao(cyclicBarrier)); - Thread thread3 = new Thread(new Acao(cyclicBarrier)); + // Thread Creation + Thread thread1 = new Thread(new Action(cyclicBarrier)); + Thread thread2 = new Thread(new Action(cyclicBarrier)); + Thread thread3 = new Thread(new Action(cyclicBarrier)); - // Início de execução das threads + // Threads start running thread1.start(); thread2.start(); thread3.start(); diff --git a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java index 90a284e..b1e4231 100644 --- a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java +++ b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java @@ -14,14 +14,14 @@ public static void main(String[] args) { queue.offerFirst("ABC", 1, TimeUnit.SECONDS); queue.offerLast("DEF", 1, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Não conseguiu inserir em menos de 1 segundo."); + System.out.println("Failed to insert in less than 1 second."); } try { queue.pollFirst(1, TimeUnit.SECONDS); queue.pollLast(1, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Não conseguiu remover em menos de 1 segundo."); + System.out.println("Failed to remove in less than 1 second."); } // end::code[] } diff --git a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java index 801e52d..fab9c65 100644 --- a/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java +++ b/src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java @@ -13,13 +13,13 @@ public static void main(String[] args) { try { queue.offer("ABC", 1, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Não conseguiu inserir em menos de 1 segundo."); + System.out.println("Failed to insert in less than 1 second."); } try { queue.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Não conseguiu remover em menos de 1 segundo."); + System.out.println("Failed to remove in less than 1 second."); } // end::code[] } diff --git a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThread.java b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThread.java index dbd6f05..cb30184 100644 --- a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThread.java +++ b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThread.java @@ -11,10 +11,10 @@ public static void main(String[] args) { // tag::code[] ScheduledExecutorService executor = null; try { - executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread - System.out.println("Agora: " + LocalTime.now()); // imprime a hora atual + executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler + System.out.println("Now: " + LocalTime.now()); // print the current time - executor.schedule(() -> System.out.println("Execução: " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution: " + LocalTime.now()), 3, TimeUnit.SECONDS); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadCallable.java b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadCallable.java index 470bd63..31a5af4 100644 --- a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadCallable.java +++ b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadCallable.java @@ -13,15 +13,15 @@ public static void main(String[] args) { // tag::code[] ScheduledExecutorService executor = null; try { - executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread - System.out.println("Antes do agendamento: " + LocalTime.now()); - ScheduledFuture retorno = executor.schedule(() -> "Execução: " + LocalTime.now(), 3, TimeUnit.SECONDS); - System.out.println("Depois do agendamento: " + LocalTime.now()); + executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler + System.out.println("Before Scheduling: " + LocalTime.now()); + ScheduledFuture futureReturn = executor.schedule(() -> "Execution: " + LocalTime.now(), 3, TimeUnit.SECONDS); + System.out.println("After Scheduling: " + LocalTime.now()); - System.out.println(retorno.get()); // fica parado aqui esperando o retorno - System.out.println("Depois da execução: " + LocalTime.now()); + System.out.println(futureReturn.get()); // stands here waiting for the return + System.out.println("After execution: " + LocalTime.now()); } catch (InterruptedException | ExecutionException e) { - System.out.println("Erro ao fazer .get()"); + System.out.println("Error doing .get()"); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedDelay.java b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedDelay.java index bfcb610..1f4a8ab 100644 --- a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedDelay.java +++ b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedDelay.java @@ -11,15 +11,15 @@ public class Schedule_SingleThreadFixedDelay { public static void main(String[] args) { ScheduledExecutorService executor = null; try { - executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread - System.out.println("Antes do agendamento: " + LocalTime.now()); // imprime a hora atual - executor.scheduleWithFixedDelay(() -> System.out.println("Execução: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS); - System.out.println("Após do agendamento: " + LocalTime.now()); // imprime a hora atual - sleep(); // aguarda um tempo para ser possível enxergar as execuções - System.out.println("Após o sleep de 10 segundos: " + LocalTime.now()); // imprime a hora atual + executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler + System.out.println("Before Scheduling: " + LocalTime.now()); // print the current time + executor.scheduleWithFixedDelay(() -> System.out.println("Execution: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS); + System.out.println("After Scheduling: " + LocalTime.now()); // print the current time + sleep(); // waits a while to be able to see the executions + System.out.println("After 10 seconds sleep: " + LocalTime.now()); // print the current time } finally { if (executor != null) { - System.out.println("Invocando shutdown no executor."); + System.out.println("Invoking shutdown on executor."); executor.shutdown(); } } diff --git a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedRate.java b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedRate.java index b7f4cc4..134d32e 100644 --- a/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedRate.java +++ b/src/org/j6toj8/concurrency/executetasks/Schedule_SingleThreadFixedRate.java @@ -11,15 +11,15 @@ public class Schedule_SingleThreadFixedRate { public static void main(String[] args) { ScheduledExecutorService executor = null; try { - executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread - System.out.println("Antes do agendamento: " + LocalTime.now()); // imprime a hora atual - executor.scheduleAtFixedRate(() -> System.out.println("Execução: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS); - System.out.println("Após do agendamento: " + LocalTime.now()); // imprime a hora atual - sleep(); // aguarda um tempo para ser possível enxergar as execuções - System.out.println("Após o sleep de 10 segundos: " + LocalTime.now()); // imprime a hora atual + executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler + System.out.println("Before Scheduling: " + LocalTime.now()); // print the current time + executor.scheduleAtFixedRate(() -> System.out.println("Execution: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS); + System.out.println("After Scheduling: " + LocalTime.now()); // print the current time + sleep(); // waits a while to be able to see the executions + System.out.println("After 10 seconds sleep: " + LocalTime.now()); // print the current time } finally { if (executor != null) { - System.out.println("Invocando shutdown no executor."); + System.out.println("Invoking shutdown on executor."); executor.shutdown(); } } diff --git a/src/org/j6toj8/concurrency/executetasks/TasksMulti_CachedThreadPool.java b/src/org/j6toj8/concurrency/executetasks/TasksMulti_CachedThreadPool.java index 8bf6f38..dd42fb8 100644 --- a/src/org/j6toj8/concurrency/executetasks/TasksMulti_CachedThreadPool.java +++ b/src/org/j6toj8/concurrency/executetasks/TasksMulti_CachedThreadPool.java @@ -9,12 +9,12 @@ public static void main(String[] args) { // tag::code[] ExecutorService executor = null; try { - executor = Executors.newCachedThreadPool(); // executor com cache de threads - executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 4 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 5 - Thread do Executor: " + Thread.currentThread().getName())); + executor = Executors.newCachedThreadPool(); // thread cached executor + executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 4 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 5 - Executor Thread: " + Thread.currentThread().getName())); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/TasksMulti_FixedThreadPool.java b/src/org/j6toj8/concurrency/executetasks/TasksMulti_FixedThreadPool.java index 67d9970..d79d4c1 100644 --- a/src/org/j6toj8/concurrency/executetasks/TasksMulti_FixedThreadPool.java +++ b/src/org/j6toj8/concurrency/executetasks/TasksMulti_FixedThreadPool.java @@ -9,12 +9,12 @@ public static void main(String[] args) { // tag::code[] ExecutorService executor = null; try { - executor = Executors.newFixedThreadPool(2); // executor com duas threads - executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 4 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 5 - Thread do Executor: " + Thread.currentThread().getName())); + executor = Executors.newFixedThreadPool(2); // two thread executor + executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 4 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 5 - Executor Thread: " + Thread.currentThread().getName())); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/TasksMulti_ScheduledThreadPool.java b/src/org/j6toj8/concurrency/executetasks/TasksMulti_ScheduledThreadPool.java index c66209f..4c4578b 100644 --- a/src/org/j6toj8/concurrency/executetasks/TasksMulti_ScheduledThreadPool.java +++ b/src/org/j6toj8/concurrency/executetasks/TasksMulti_ScheduledThreadPool.java @@ -11,14 +11,14 @@ public static void main(String[] args) { // tag::code[] ScheduledExecutorService executor = null; try { - executor = Executors.newScheduledThreadPool(2); // executor de agendamento com duas threads - System.out.println("Agora: " + LocalTime.now()); // imprime a hora atual + executor = Executors.newScheduledThreadPool(2); // two thread scheduling executor + System.out.println("Now: " + LocalTime.now()); // print the current time - executor.schedule(() -> System.out.println("Execução 1: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); - executor.schedule(() -> System.out.println("Execução 2: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); - executor.schedule(() -> System.out.println("Execução 3: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); - executor.schedule(() -> System.out.println("Execução 4: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); - executor.schedule(() -> System.out.println("Execução 5: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution 1: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution 2: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution 3: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution 4: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); + executor.schedule(() -> System.out.println("Execution 5: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_RunnableCallable.java b/src/org/j6toj8/concurrency/executetasks/Tasks_RunnableCallable.java index 09bcbee..aefdcc8 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_RunnableCallable.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_RunnableCallable.java @@ -11,17 +11,17 @@ public static void main(String[] args) { try { executor = Executors.newSingleThreadExecutor(); - // tarefa sem retorno, instância de Runnable + // task without return, instance of Runnable executor.submit(() -> System.out.println("Runnable")); - // tarefa com retorno, instância de Callable + // task with return, instance of Callable executor.submit(() -> "Callable"); - - // tarefa que lança uma Exception deve ser Callable, logo deve ter retorno + + // task that throws an Exception must be Callable, then needs to return executor.submit(() -> {Thread.sleep(1); return "Callable";}); - // tarefa que lança uma Exception, mas não declara retorno - // NÃO COMPILA pois é interpretada como Runnable + // task that throws an Exception, but declares no return + // NOT COMPILING as it is interpreted as Runnable executor.submit(() -> Thread.sleep(1)); } finally { diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_ShutdownNow.java b/src/org/j6toj8/concurrency/executetasks/Tasks_ShutdownNow.java index 6b6dd74..7237948 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_ShutdownNow.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_ShutdownNow.java @@ -10,11 +10,11 @@ public static void main(String[] args) { ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); - System.out.println("Thread Principal: " + Thread.currentThread().getName()); + executor.execute(() -> System.out.println("Executor Thread: " + Thread.currentThread().getName())); + System.out.println("Main Thread: " + Thread.currentThread().getName()); } finally { if (executor != null) { - executor.shutdownNow(); // TENTA encerrar todas as threads imediatamente + executor.shutdownNow(); // TRIES to shut down all threads immediately } } // end::code[] diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThread.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThread.java index 01cccab..c03aaed 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThread.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThread.java @@ -9,9 +9,9 @@ public static void main(String[] args) { // tag::code[] ExecutorService executor = null; try { - executor = Executors.newSingleThreadExecutor(); // executor com uma única thread - executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); - System.out.println("Thread Principal: " + Thread.currentThread().getName()); + executor = Executors.newSingleThreadExecutor(); // single thread executor + executor.execute(() -> System.out.println("Executor Thread: " + Thread.currentThread().getName())); + System.out.println("Main Thread: " + Thread.currentThread().getName()); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadAwaitTermination.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadAwaitTermination.java index d59c1e9..b440cb6 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadAwaitTermination.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadAwaitTermination.java @@ -14,9 +14,9 @@ public static void main(String[] args) { try { executor = Executors.newSingleThreadExecutor(); - executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName())); } finally { if (executor != null) { executor.shutdown(); @@ -25,11 +25,11 @@ public static void main(String[] args) { if (executor != null) { try { - System.out.println("Tarefas finalizadas? " + executor.isTerminated()); + System.out.println("Tasks completed? " + executor.isTerminated()); executor.awaitTermination(1, TimeUnit.SECONDS); - System.out.println("Tarefas finalizadas? " + executor.isTerminated()); + System.out.println("Tasks completed? " + executor.isTerminated()); } catch (InterruptedException e) { - System.out.println("Erro de interrupção."); + System.out.println("Interruption error."); } } // end::code[] diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadCallable.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadCallable.java index 1c4ad73..b535ef3 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadCallable.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadCallable.java @@ -12,12 +12,12 @@ public static void main(String[] args) { ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - Future retornoDaTarefa = executor.submit(() -> "String que será retornada"); - - // O .get() abaixo irá esperar a tarefa finalizar para pegar seu retorno - System.out.println("Retorno da tarefa: " + retornoDaTarefa.get()); + Future taskReturn = executor.submit(() -> "String to be returned"); + + // The .get() below will wait for the task to finish to get its return + System.out.println("Task Return: " + taskReturn.get()); } catch (InterruptedException | ExecutionException e) { - System.out.println("Execução interrompida."); + System.out.println("Execution stopped."); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadFuture.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadFuture.java index bdaa846..b98f1bd 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadFuture.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadFuture.java @@ -11,16 +11,16 @@ public static void main(String[] args) { ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - Future tarefa = executor.submit(() -> System.out.println("Tarefa executando")); + Future task = executor.submit(() -> System.out.println("Task running")); - // verifica se a tarefa está finalizada - System.out.println("Tarefa já finalizada? " + tarefa.isDone()); - - // tenta cancelar a tarefa - System.out.println("Tentando cancelar a tarefa. Conseguiu? " + tarefa.cancel(true)); - - // verifica se a tarefa foi cancelada - System.out.println("Tarefa foi cancelada? " + tarefa.isCancelled()); + // check if the task is finished + System.out.println("Task already completed? " + task.isDone()); + + // try to cancel the task + System.out.println("Trying to cancel the task. Got it? " + task.cancel(true)); + + // check if the task has been canceled + System.out.println("Task was canceled? " + task.isCancelled()); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAll.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAll.java index c6a0dfa..6e5d662 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAll.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAll.java @@ -12,23 +12,23 @@ public class Tasks_SingleThreadInvokeAll { public static void main(String[] args) { // tag::code[] - List> tarefas = new ArrayList>(); - tarefas.add(() -> "Tarefa 1 executada na thread " + Thread.currentThread().getName()); - tarefas.add(() -> "Tarefa 2 executada na thread " + Thread.currentThread().getName()); - tarefas.add(() -> "Tarefa 3 executada na thread " + Thread.currentThread().getName()); + List> tasks = new ArrayList>(); + tasks.add(() -> "Task 1 performed on thread" + Thread.currentThread().getName()); + tasks.add(() -> "Task 2 performed on thread" + Thread.currentThread().getName()); + tasks.add(() -> "Task 3 performed on thread" + Thread.currentThread().getName()); ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - // invokeAll devolve todos os retornos das tarefas executadas em uma lista - List> retornos = executor.invokeAll(tarefas); + // invokeAll returns all returns of tasks performed in a list + List> returnList = executor.invokeAll(tasks); - for (Future retorno : retornos) { - System.out.println("Retorno da tarefa: " + retorno.get()); + for (Future futureReturn : returnList) { + System.out.println("Task Return: " + futureReturn.get()); } } catch (InterruptedException | ExecutionException e) { - System.out.println("Execução interrompida."); + System.out.println("Execution stopped."); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAny.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAny.java index 18da6cc..6bdcb88 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAny.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadInvokeAny.java @@ -12,21 +12,21 @@ public class Tasks_SingleThreadInvokeAny { public static void main(String[] args) { // tag::code[] - List> tarefas = new ArrayList>(); - tarefas.add(() -> "Tarefa 1 executada na thread " + Thread.currentThread().getName()); - tarefas.add(() -> "Tarefa 2 executada na thread " + Thread.currentThread().getName()); - tarefas.add(() -> "Tarefa 3 executada na thread " + Thread.currentThread().getName()); + List> tasks = new ArrayList>(); + tasks.add(() -> "Task 1 performed on thread" + Thread.currentThread().getName()); + tasks.add(() -> "Task 2 performed on thread" + Thread.currentThread().getName()); + tasks.add(() -> "Task 3 performed on thread" + Thread.currentThread().getName()); ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - // invokeAny devolve apenas uma das tarefas que finalizou e interrompe as outras - String retorno = executor.invokeAny(tarefas); - System.out.println("Retorno da tarefa: " + retorno); + // invokeAny returns only one of the completed tasks and interrupts the others + String singleReturn = executor.invokeAny(tasks); + System.out.println("Task Return: " + singleReturn); } catch (InterruptedException | ExecutionException e) { - System.out.println("Execução interrompida."); + System.out.println("Execution stopped."); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadManyTasks.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadManyTasks.java index 38b4c28..03dc7c1 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadManyTasks.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadManyTasks.java @@ -9,11 +9,11 @@ public static void main(String[] args) { // tag::code[] ExecutorService executor = null; try { - executor = Executors.newSingleThreadExecutor(); // executor com uma única thread - executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName())); - executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName())); - System.out.println("Thread Principal: " + Thread.currentThread().getName()); + executor = Executors.newSingleThreadExecutor(); // executor with a single thread + executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName())); + executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName())); + System.out.println("Main Thread: " + Thread.currentThread().getName()); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadSubmit.java b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadSubmit.java index 8b48251..9e04010 100644 --- a/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadSubmit.java +++ b/src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadSubmit.java @@ -11,12 +11,12 @@ public static void main(String[] args) { ExecutorService executor = null; try { executor = Executors.newSingleThreadExecutor(); - Future tarefa = executor.submit(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); + Future task = executor.submit(() -> System.out.println("Executor Thread: " + Thread.currentThread().getName())); - System.out.println("Tarefa já finalizada? " + tarefa.isDone()); - System.out.println("Tarefa já finalizada? " + tarefa.isDone()); - System.out.println("Tarefa já finalizada? " + tarefa.isDone()); - System.out.println("Tarefa já finalizada? " + tarefa.isDone()); + System.out.println("Task already completed? " + task.isDone()); + System.out.println("Task already completed? " + task.isDone()); + System.out.println("Task already completed? " + task.isDone()); + System.out.println("Task already completed? " + task.isDone()); } finally { if (executor != null) { executor.shutdown(); diff --git a/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveAction.java b/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveAction.java index c358ee0..151c0d6 100644 --- a/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveAction.java +++ b/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveAction.java @@ -9,58 +9,57 @@ public class ForkJoin_RecursiveAction { // tag::code[] - // Classe que representa a tarefa que será executada - static class ImpressaoDeStrings extends RecursiveAction { + // Class that represents the task that will be performed + static class StringPrinterAction extends RecursiveAction { - private String stringParaImprimir; // String que será impressa + private String stringToPrint; - public ImpressaoDeStrings(String stringParaImprimir) { - this.stringParaImprimir = stringParaImprimir; + public StringPrinterAction(String stringToPrint) { + this.stringToPrint = stringToPrint; } @Override protected void compute() { - if (stringParaImprimir.length() < 10) { - // se a String tiver menos de 10 caracteres, será impressa - System.out.println(Thread.currentThread().getName() + " - " + stringParaImprimir); + if (stringToPrint.length() < 10) { + // if String is less than 10 characters, will print + System.out.println(Thread.currentThread().getName() + " - " + stringToPrint); } else { - // caso contrário, são criadas duas novas tarefas, uma com a primeira metade da String - // e outra com a segunda metade da String - List novasTarefas = divideEmDuasTarefas(); - - // Invoca a execução das duas tarefas criadas - ForkJoinTask.invokeAll(novasTarefas); + // otherwise, two new tasks are created, one with the first half of String and one with the second half of String + List newTasks = divideInTwoTasks(); + + // Invoke execution of two created tasks + ForkJoinTask.invokeAll(newTasks); } } - private List divideEmDuasTarefas() { - // esse método divide a String em duas partes e cria duas novas tarefas - // cada uma das tarefas recebe uma parte da String + private List divideInTwoTasks() { + // this method splits the string into two parts and creates two new tasks + // each task gets a part of the String - int tamanhoDaString = stringParaImprimir.length(); - int meioDaString = tamanhoDaString / 2; + int stringSize = stringToPrint.length(); + int stringMiddle = stringSize / 2; - String primeiraMetade = stringParaImprimir.substring(0, meioDaString); - String segundaMetade = stringParaImprimir.substring(meioDaString); + String firstHalf = stringToPrint.substring(0, stringMiddle); + String secondHalf = stringToPrint.substring(stringMiddle); - List acoes = new ArrayList(); - acoes.add(new ImpressaoDeStrings(primeiraMetade)); - acoes.add(new ImpressaoDeStrings(segundaMetade)); - return acoes; + List actions = new ArrayList(); + actions.add(new StringPrinterAction(firstHalf)); + actions.add(new StringPrinterAction(secondHalf)); + return actions; } } public static void main(String[] args) { - // string que queremos imprimir - String stringParaImprimir = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - // tarefa principal que será executada - ImpressaoDeStrings tarefa = new ImpressaoDeStrings(stringParaImprimir); - - // criação do ForkJoinPool e execução da tarefa + // string we want to print + String stringToPrint= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + // main task to be performed + StringPrinterAction task = new StringPrinterAction(stringToPrint); + + // ForkJoinPool creation and task execution ForkJoinPool forkJoinPool = new ForkJoinPool(); - forkJoinPool.invoke(tarefa); + forkJoinPool.invoke(task); } // end::code[] diff --git a/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveTask.java b/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveTask.java index b48648d..a66f830 100644 --- a/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveTask.java +++ b/src/org/j6toj8/concurrency/forkjoin/ForkJoin_RecursiveTask.java @@ -4,79 +4,78 @@ import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; -import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveTask; public class ForkJoin_RecursiveTask { // tag::code[] - // Classe que representa a tarefa que será executada - static class ImpressaoDeStrings extends RecursiveTask { + // Class that represents the task that will be performed + static class StringPrinter extends RecursiveTask { - private String stringParaImprimir; // String que será impressa + private String stringToPrint; - public ImpressaoDeStrings(String stringParaImprimir) { - this.stringParaImprimir = stringParaImprimir; + public StringPrinter(String stringToPrint) { + this.stringToPrint = stringToPrint; } @Override protected Integer compute() { - if (stringParaImprimir.length() < 10) { - // se a String tiver menos de 10 caracteres, será impressa - System.out.println(Thread.currentThread().getName() + " - " + stringParaImprimir); - - // retornamos a quantidade de caracteres impressos - return stringParaImprimir.length(); + if (stringToPrint.length() < 10) { + // if String is less than 10 characters, will print + System.out.println(Thread.currentThread().getName() + " - " + stringToPrint); + + // return the amount of characters printed + return stringToPrint.length(); } else { - // caso contrário, são criadas duas novas tarefas, uma com a primeira metade da String - // e outra com a segunda metade da String - List novasTarefas = divideEmDuasTarefas(); - ImpressaoDeStrings tarefa1 = novasTarefas.get(0); - ImpressaoDeStrings tarefa2 = novasTarefas.get(1); - - // 'fork' irá enviar a tarefa1 para ser executada em uma nova thread - ForkJoinTask primeiraTarefa = tarefa1.fork(); - - // 'compute' irá executar a tarefa2 nessa mesma thread - Integer resultadoDaTarefa2 = tarefa2.compute(); - - // 'join' irá pegar o resultado da tafera1 que estava sendo executada em outra thread - Integer resultadoDaTarefa1 = primeiraTarefa.join(); - - // retornamos a soma dos resultados, pois é a quantidade de carateres impressos - return resultadoDaTarefa2 + resultadoDaTarefa1; + // otherwise, two new tasks are created, one with the first half of String and one with the second half of String + List newTasks = divideInTwoTasks(); + StringPrinter task1 = newTasks.get(0); + StringPrinter task2 = newTasks.get(1); + + // 'fork' will send task1 to run on a new thread + ForkJoinTask firstTask = task1.fork(); + + // 'compute' will execute task2 on this same thread + Integer taskResult2 = task2.compute(); + + // 'join' will get the result of task1 that was running on another thread + Integer taskResult1 = firstTask.join(); + + // return the sum of the results because it is the number of characters printed + return taskResult2 + taskResult1; } } - private List divideEmDuasTarefas() { - // esse método divide a String em duas partes e cria duas novas tarefas - // cada uma das tarefas recebe uma parte da String - - int tamanhoDaString = stringParaImprimir.length(); - int meioDaString = tamanhoDaString / 2; - - String primeiraMetade = stringParaImprimir.substring(0, meioDaString); - String segundaMetade = stringParaImprimir.substring(meioDaString); - - List acoes = new ArrayList(); - acoes.add(new ImpressaoDeStrings(primeiraMetade)); - acoes.add(new ImpressaoDeStrings(segundaMetade)); - return acoes; + private List divideInTwoTasks() { + // this method splits the string into two parts and creates two new tasks + // each task gets a part of the String + + int stringSize = stringToPrint.length(); + int stringMiddle = stringSize / 2; + + String firstHalf = stringToPrint.substring(0, stringMiddle); + String secondHalf = stringToPrint.substring(stringMiddle); + + List actions = new ArrayList(); + actions.add(new StringPrinter(firstHalf)); + actions.add(new StringPrinter(secondHalf)); + return actions; } } public static void main(String[] args) { - // string que queremos imprimir - String stringParaImprimir = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - // tarefa principal que será executada - ImpressaoDeStrings tarefa = new ImpressaoDeStrings(stringParaImprimir); - - // criação do ForkJoinPool e execução da tarefa + // string we want to print + String stringToPrint= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + // main task to be performed + StringPrinter task = new StringPrinter(stringToPrint); + + // ForkJoinPool creation and task execution ForkJoinPool forkJoinPool = new ForkJoinPool(); - Integer resultado = forkJoinPool.invoke(tarefa); - System.out.println("Resultado da execução: " + resultado); + Integer result = forkJoinPool.invoke(task); + System.out.println("Execution result: " + result); + } // end::code[] diff --git a/src/org/j6toj8/concurrency/locks/Locks_Fair.java b/src/org/j6toj8/concurrency/locks/Locks_Fair.java index 6269e21..f11eefa 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_Fair.java +++ b/src/org/j6toj8/concurrency/locks/Locks_Fair.java @@ -7,12 +7,12 @@ public class Locks_Fair { public static void main(String[] args) { // tag::code[] - Lock lock = new ReentrantLock(true); // lock "justo" + Lock lock = new ReentrantLock(true); // "fair" lock try { lock.lock(); System.out.println("ABC"); } finally { - lock.unlock(); // desfaz o lock + lock.unlock(); // undo the lock } // end::code[] } diff --git a/src/org/j6toj8/concurrency/locks/Locks_LockTwice.java b/src/org/j6toj8/concurrency/locks/Locks_LockTwice.java index a37fa2b..4b6a139 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_LockTwice.java +++ b/src/org/j6toj8/concurrency/locks/Locks_LockTwice.java @@ -13,8 +13,8 @@ public static void main(String[] args) { lock.lock(); System.out.println("ABC"); } finally { - lock.unlock(); // desfaz o primeiro lock - lock.unlock(); // desfaz o segundo lock + lock.unlock(); // undo the first lock + lock.unlock(); // undo the second lock } // end::code[] } diff --git a/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java b/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java index dcf1260..838051e 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java +++ b/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java @@ -7,11 +7,11 @@ public class Locks_ReadWriteLock { // tag::code[] - static class Acao implements Runnable { + static class Action implements Runnable { private ReadWriteLock lock; - public Acao(ReadWriteLock reentrantLock) { + public Action(ReadWriteLock reentrantLock) { this.lock = reentrantLock; } @@ -20,7 +20,7 @@ public void run() { Lock readLock = lock.readLock(); if (readLock.tryLock()) { try { - System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura"); + System.out.println(Thread.currentThread().getName() + ": Got the read Lock"); } finally { readLock.unlock(); } @@ -29,7 +29,7 @@ public void run() { Lock writeLock = lock.writeLock(); if (writeLock.tryLock()) { try { - System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita"); + System.out.println(Thread.currentThread().getName() + ": Got the write Lock"); } finally { writeLock.unlock(); } @@ -39,13 +39,13 @@ public void run() { public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); - - // Criação das threads - Thread thread1 = new Thread(new Acao(lock)); - Thread thread2 = new Thread(new Acao(lock)); - Thread thread3 = new Thread(new Acao(lock)); - - // Execução das threads + + // Thread creation + Thread thread1 = new Thread(new Action(lock)); + Thread thread2 = new Thread(new Action(lock)); + Thread thread3 = new Thread(new Action(lock)); + + // Thread Execution thread1.start(); thread2.start(); thread3.start(); diff --git a/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java b/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java index 726c064..9d84c87 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java +++ b/src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java @@ -7,11 +7,11 @@ public class Locks_ReadWriteLockInverted { // tag::code[] - static class Acao implements Runnable { + static class Action implements Runnable { private ReadWriteLock lock; - public Acao(ReadWriteLock reentrantLock) { + public Action(ReadWriteLock reentrantLock) { this.lock = reentrantLock; } @@ -20,7 +20,7 @@ public void run() { Lock writeLock = lock.writeLock(); if (writeLock.tryLock()) { try { - System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita"); + System.out.println(Thread.currentThread().getName() + ": Got the read Lock"); } finally { writeLock.unlock(); } @@ -29,7 +29,7 @@ public void run() { Lock readLock = lock.readLock(); if (readLock.tryLock()) { try { - System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura"); + System.out.println(Thread.currentThread().getName() + ": Got the write Lock"); } finally { readLock.unlock(); } @@ -39,13 +39,13 @@ public void run() { public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); - - // Criação das threads - Thread thread1 = new Thread(new Acao(lock)); - Thread thread2 = new Thread(new Acao(lock)); - Thread thread3 = new Thread(new Acao(lock)); - - // Execução das threads + + // Thread creation + Thread thread1 = new Thread(new Action(lock)); + Thread thread2 = new Thread(new Action(lock)); + Thread thread3 = new Thread(new Action(lock)); + + // Thread Execution thread1.start(); thread2.start(); thread3.start(); diff --git a/src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java b/src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java index e7874ea..b072054 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java +++ b/src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java @@ -9,10 +9,10 @@ public static void main(String[] args) { // tag::code[] Lock lock = new ReentrantLock(); try { - lock.lock(); // apenas uma thread obtém o lock por vez + lock.lock(); // only one thread gets lock at a time System.out.println("ABC"); } finally { - lock.unlock(); // desfaz o lock + lock.unlock(); // undo the lock } // end::code[] } diff --git a/src/org/j6toj8/concurrency/locks/Locks_TryLock.java b/src/org/j6toj8/concurrency/locks/Locks_TryLock.java index 758e0c3..fe2ea92 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_TryLock.java +++ b/src/org/j6toj8/concurrency/locks/Locks_TryLock.java @@ -8,13 +8,13 @@ public class Locks_TryLock { public static void main(String[] args) { // tag::code[] Lock lock = new ReentrantLock(); - boolean temLock = lock.tryLock(); + boolean hasLock = lock.tryLock(); - if (temLock) { + if (hasLock) { try { System.out.println("ABC"); } finally { - lock.unlock(); // desfaz o lock + lock.unlock(); // undo the lock } } else { System.out.println("DEF"); diff --git a/src/org/j6toj8/concurrency/locks/Locks_TryLockMultithread.java b/src/org/j6toj8/concurrency/locks/Locks_TryLockMultithread.java index a70ea33..5d5f23d 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_TryLockMultithread.java +++ b/src/org/j6toj8/concurrency/locks/Locks_TryLockMultithread.java @@ -6,11 +6,11 @@ public class Locks_TryLockMultithread { // tag::code[] - static class Acao implements Runnable { + static class Action implements Runnable { private Lock lock; - public Acao(Lock reentrantLock) { + public Action(Lock reentrantLock) { this.lock = reentrantLock; } @@ -18,7 +18,7 @@ public Acao(Lock reentrantLock) { public void run() { if (lock.tryLock()) { try { - System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock"); + System.out.println(Thread.currentThread().getName() + ": Got the Lock"); } finally { lock.unlock(); } @@ -28,13 +28,13 @@ public void run() { public static void main(String[] args) { Lock lock = new ReentrantLock(); - - // Criação das threads - Thread thread1 = new Thread(new Acao(lock)); - Thread thread2 = new Thread(new Acao(lock)); - Thread thread3 = new Thread(new Acao(lock)); - - // Execução das threads + + // Thread creation + Thread thread1 = new Thread(new Action(lock)); + Thread thread2 = new Thread(new Action(lock)); + Thread thread3 = new Thread(new Action(lock)); + + // Thread creation thread1.start(); thread2.start(); thread3.start(); diff --git a/src/org/j6toj8/concurrency/locks/Locks_TryLockTimeout.java b/src/org/j6toj8/concurrency/locks/Locks_TryLockTimeout.java index d0c1a3e..b400fce 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_TryLockTimeout.java +++ b/src/org/j6toj8/concurrency/locks/Locks_TryLockTimeout.java @@ -10,19 +10,19 @@ public static void main(String[] args) { // tag::code[] Lock lock = new ReentrantLock(); - boolean temLock = false; + boolean hasLock = false; try { - // tenta obter o lock por no máximo 1 segundo - temLock = lock.tryLock(1, TimeUnit.SECONDS); + // try to lock for a maximum of 1 second + hasLock = lock.tryLock(1, TimeUnit.SECONDS); } catch (InterruptedException e) { - System.out.println("Não obteve o Lock"); + System.out.println("Didn't get the lock"); } - if (temLock) { + if (hasLock) { try { System.out.println("ABC"); } finally { - lock.unlock(); // desfaz o lock + lock.unlock(); // undo the lock } } else { System.out.println("DEF"); diff --git a/src/org/j6toj8/concurrency/locks/Locks_UnlockWithoutLock.java b/src/org/j6toj8/concurrency/locks/Locks_UnlockWithoutLock.java index d9f3b18..37fc8a0 100644 --- a/src/org/j6toj8/concurrency/locks/Locks_UnlockWithoutLock.java +++ b/src/org/j6toj8/concurrency/locks/Locks_UnlockWithoutLock.java @@ -11,7 +11,7 @@ public static void main(String[] args) { try { System.out.println("ABC"); } finally { - lock.unlock(); // lança exceção, pois não há lock + lock.unlock(); // throws exception as there is no lock } // end::code[] } diff --git a/src/org/j6toj8/fileio/fileimprovements/Improvements_Find.java b/src/org/j6toj8/fileio/fileimprovements/Improvements_Find.java index 74d16c0..03e83b8 100644 --- a/src/org/j6toj8/fileio/fileimprovements/Improvements_Find.java +++ b/src/org/j6toj8/fileio/fileimprovements/Improvements_Find.java @@ -10,15 +10,15 @@ public class Improvements_Find { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - System.out.println("\nTodos os arquivos, ignorando diretórios, até o segundo nível: "); - // ao chamar o find: - // primeiro argumento: o path inicial - // segundo argumento: o limite de profundidade - // terceiro argumento: expressão lambda para filtrar + System.out.println("\nAll files, skipping directories, up to the second level: "); + // when calling find: + // first argument: the initial path + // second argument: the depth limit + // third argument: lambda expression to filter Files.find(path, 2, (p, a) -> a.isRegularFile()) .forEach(System.out::println); } catch (IOException e) { diff --git a/src/org/j6toj8/fileio/fileimprovements/Improvements_Lines.java b/src/org/j6toj8/fileio/fileimprovements/Improvements_Lines.java index a8256f3..23fe093 100644 --- a/src/org/j6toj8/fileio/fileimprovements/Improvements_Lines.java +++ b/src/org/j6toj8/fileio/fileimprovements/Improvements_Lines.java @@ -10,21 +10,21 @@ public class Improvements_Lines { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos", "subpasta1", "arquivo11.txt"); + Path path = Paths.get(userHome, "files", "subfolder1", "file11.txt"); System.out.println("Path: " + path); try { - System.out.println("\nConteúdo do arquivo: "); - Files.lines(path) // recupera todas as linhas do arquivo como Stream + System.out.println("\nFile content: "); + Files.lines(path) // retrieves all file lines as Stream .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } try { - System.out.println("\nConteúdo do arquivo maior que 2: "); + System.out.println("\nFile contents greater than 2: "); Files.lines(path) - .filter(s -> Integer.parseInt(s) > 2) // filtra maior que 2 + .filter(s -> Integer.parseInt(s) > 2) // filters greater than 2 .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); diff --git a/src/org/j6toj8/fileio/fileimprovements/Improvements_List.java b/src/org/j6toj8/fileio/fileimprovements/Improvements_List.java index f355aa5..7df292c 100644 --- a/src/org/j6toj8/fileio/fileimprovements/Improvements_List.java +++ b/src/org/j6toj8/fileio/fileimprovements/Improvements_List.java @@ -10,11 +10,11 @@ public class Improvements_List { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - System.out.println("\nListagem do diretório: "); + System.out.println("\nDirectory listing: "); Files.list(path) .forEach(System.out::println); } catch (IOException e) { @@ -22,7 +22,7 @@ public static void main(String[] args) { } try { - System.out.println("\nListagem do diretório, apenas arquivos: "); + System.out.println("\nDirectory listing, files only: "); Files.list(path) .filter(p -> Files.isRegularFile(p)) .forEach(System.out::println); diff --git a/src/org/j6toj8/fileio/fileimprovements/Improvements_Walk.java b/src/org/j6toj8/fileio/fileimprovements/Improvements_Walk.java index e486075..3b2a0f7 100644 --- a/src/org/j6toj8/fileio/fileimprovements/Improvements_Walk.java +++ b/src/org/j6toj8/fileio/fileimprovements/Improvements_Walk.java @@ -10,19 +10,19 @@ public class Improvements_Walk { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - System.out.println("\nTodos os arquivos e diretórios: "); - Files.walk(path) // cria o stream - .forEach(System.out::println); // imprime no console + System.out.println("\nAll files and directories: "); + Files.walk(path) // creates a stream + .forEach(System.out::println); // prints on console } catch (IOException e) { e.printStackTrace(); } try { - System.out.println("\nOs primeiro 5 arquivos e diretórios: "); + System.out.println("\nThe first 5 files and directories: "); Files.walk(path) .limit(5) .forEach(System.out::println); diff --git a/src/org/j6toj8/fileio/fileimprovements/Improvements_WalkDepth.java b/src/org/j6toj8/fileio/fileimprovements/Improvements_WalkDepth.java index 68d3e3b..3c2e47d 100644 --- a/src/org/j6toj8/fileio/fileimprovements/Improvements_WalkDepth.java +++ b/src/org/j6toj8/fileio/fileimprovements/Improvements_WalkDepth.java @@ -11,11 +11,11 @@ public class Improvements_WalkDepth { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - System.out.println("\nArquivos e Links simbólicos até o segundo nível: "); + System.out.println("\nSymbolic files and links to the second level: "); Files.walk(path, 2, FileVisitOption.FOLLOW_LINKS) .forEach(System.out::println); } catch (IOException e) { diff --git a/src/org/j6toj8/fileio/files/Files_BasicFileAttributeView.java b/src/org/j6toj8/fileio/files/Files_BasicFileAttributeView.java index 7d1d740..d35d864 100644 --- a/src/org/j6toj8/fileio/files/Files_BasicFileAttributeView.java +++ b/src/org/j6toj8/fileio/files/Files_BasicFileAttributeView.java @@ -16,23 +16,23 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivo.txt"); + Path path = Paths.get(userHome, "file.txt"); try { BasicFileAttributeView attributesView = Files.getFileAttributeView(path, BasicFileAttributeView.class); - BasicFileAttributes attributesAntigos = attributesView.readAttributes(); + BasicFileAttributes oldAttributes = attributesView.readAttributes(); - System.out.println("\nData de Criação original: " + attributesAntigos.creationTime()); - System.out.println("Último acesso original: " + attributesAntigos.lastAccessTime()); - System.out.println("Última modificação original: " + attributesAntigos.lastModifiedTime()); + System.out.println("\nOriginal creation date: " + oldAttributes.creationTime()); + System.out.println("Original last access: " + oldAttributes.lastAccessTime()); + System.out.println("Original last modified: " + oldAttributes.lastModifiedTime()); FileTime fileTime = FileTime.from(Instant.now().plusMillis(10000)); attributesView.setTimes(fileTime, fileTime, fileTime); - BasicFileAttributes attributesNovos = attributesView.readAttributes(); - System.out.println("\nData de Criação alterada: " + attributesNovos.creationTime()); - System.out.println("Último acesso alterada: " + attributesNovos.lastAccessTime()); - System.out.println("Última modificação alterada: " + attributesNovos.lastModifiedTime()); + BasicFileAttributes newAttributes = attributesView.readAttributes(); + System.out.println("\nCreation date changed: " + newAttributes.creationTime()); + System.out.println("Last access changed: " + newAttributes.lastAccessTime()); + System.out.println("Last modified changed: " + newAttributes.lastModifiedTime()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_BasicFileAttributes.java b/src/org/j6toj8/fileio/files/Files_BasicFileAttributes.java index 35ca1d8..04b2164 100644 --- a/src/org/j6toj8/fileio/files/Files_BasicFileAttributes.java +++ b/src/org/j6toj8/fileio/files/Files_BasicFileAttributes.java @@ -13,20 +13,20 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivo.txt"); + Path path = Paths.get(userHome, "file.txt"); try { BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); - System.out.println("Tamanho: " + attributes.size()); + System.out.println("Size: " + attributes.size()); - System.out.println("É diretório? " + attributes.isDirectory()); - System.out.println("É link simbólico? " + attributes.isSymbolicLink()); - System.out.println("É um arquivo comum? " + attributes.isRegularFile()); - System.out.println("Não é nenhuma das opções acima? " + attributes.isOther()); + System.out.println("Is it directory? " + attributes.isDirectory()); + System.out.println("Is it symbolic link? " + attributes.isSymbolicLink()); + System.out.println("Is it a common file? " + attributes.isRegularFile()); + System.out.println("Not any of the above? " + attributes.isOther()); - System.out.println("Data de Criação: " + attributes.creationTime()); - System.out.println("Último acesso: " + attributes.lastAccessTime()); - System.out.println("Última modificação: " + attributes.lastModifiedTime()); + System.out.println("Creation date: " + attributes.creationTime()); + System.out.println("Last acess: " + attributes.lastAccessTime()); + System.out.println("Last Modified: " + attributes.lastModifiedTime()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_Checks.java b/src/org/j6toj8/fileio/files/Files_Checks.java index 0528cb5..92a4b24 100644 --- a/src/org/j6toj8/fileio/files/Files_Checks.java +++ b/src/org/j6toj8/fileio/files/Files_Checks.java @@ -12,44 +12,44 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path1 = Paths.get(userHome, "arquivo1.txt"); - Path path2 = Paths.get(userHome, "arquivos"); + Path path1 = Paths.get(userHome, "file1.txt"); + Path path2 = Paths.get(userHome, "files"); System.out.println("Path 1: " + path1); System.out.println("Path 2: " + path2); - System.out.println("Path 1 existe? " + Files.exists(path1)); - System.out.println("Path 2 existe? " + Files.exists(path2)); + System.out.println("Path 1 exist? " + Files.exists(path1)); + System.out.println("Path 2 exist? " + Files.exists(path2)); - System.out.println("Path 1 NÃO existe? " + Files.notExists(path1)); - System.out.println("Path 2 NÃO existe? " + Files.notExists(path2)); + System.out.println("Path 1 does NOT exist? " + Files.notExists(path1)); + System.out.println("Path 2 does NOT exist? " + Files.notExists(path2)); - System.out.println("Path 1 é um diretório? " + Files.isDirectory(path1)); - System.out.println("Path 1 é um arquivo comum? " + Files.isRegularFile(path1)); - System.out.println("Path 1 é um link simbólico? " + Files.isSymbolicLink(path1)); + System.out.println("Is Path 1 a directory? " + Files.isDirectory(path1)); + System.out.println("Is Path 1 a common file? " + Files.isRegularFile(path1)); + System.out.println("Is Path 1 a symbolic link? " + Files.isSymbolicLink(path1)); - System.out.println("Aplicação possui permissão de leitura no Path 1? " + Files.isReadable(path1)); - System.out.println("Aplicação possui permissão de escrita no Path 1? " + Files.isWritable(path1)); - System.out.println("Aplicação possui permissão de execução no Path 1? " + Files.isExecutable(path1)); + System.out.println("Application has read permission on Path 1? " + Files.isReadable(path1)); + System.out.println("Application has write permission on Path 1? " + Files.isWritable(path1)); + System.out.println("Application has execution permission on Path 1? " + Files.isExecutable(path1)); try { - System.out.println("Qual o tamanho de Path 1? " + Files.size(path1)); + System.out.println("How big is Path 1? " + Files.size(path1)); } catch (IOException e1) { - // Lança exceção se o arquivo não existir + // Throw exception if file does not exist e1.printStackTrace(); } try { - System.out.println("Path 1 é oculto? " + Files.isHidden(path1)); + System.out.println("Is Path 1 hidden? " + Files.isHidden(path1)); } catch (IOException e) { - // Lança exceção se o arquivo não existir + // Throw exception if file does not exist e.printStackTrace(); } try { - System.out.println("Path 1 e Path 1 são iguais? " + Files.isSameFile(path1, path1)); + System.out.println("Are Path 1 and Path 1 the same? " + Files.isSameFile(path1, path1)); } catch (IOException e) { - // Lança exceção se o arquivo não existir + // Throw exception if file does not exist e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CopyFromPath.java b/src/org/j6toj8/fileio/files/Files_CopyFromPath.java index 89bfda9..8ea8e56 100644 --- a/src/org/j6toj8/fileio/files/Files_CopyFromPath.java +++ b/src/org/j6toj8/fileio/files/Files_CopyFromPath.java @@ -15,17 +15,16 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "copia" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "copy" + new Random().nextInt() + ".txt"; - try (FileOutputStream fos = new FileOutputStream(userHome + File.separator + nomeAleatorio)) { - Path pathParaCopia = Paths.get(userHome, "arquivo1.txt"); - Files.copy(pathParaCopia, fos); + try (FileOutputStream fos = new FileOutputStream(userHome + File.separator + randomName)) { + Path pathToCopy = Paths.get(userHome, "file1.txt"); + Files.copy(pathToCopy, fos); - Path pathCriado = Paths.get(userHome, nomeAleatorio); - System.out.println("Path criado: " + pathCriado); - System.out.println("Path criado existe?: " + Files.exists(pathCriado)); + Path createdPath = Paths.get(userHome, randomName); + System.out.println("Created Path: " + createdPath); + System.out.println("Created Path exist? " + Files.exists(createdPath)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CopyPath.java b/src/org/j6toj8/fileio/files/Files_CopyPath.java index 38ba800..e4803dc 100644 --- a/src/org/j6toj8/fileio/files/Files_CopyPath.java +++ b/src/org/j6toj8/fileio/files/Files_CopyPath.java @@ -13,22 +13,21 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path1 = Paths.get(userHome, nomeAleatorio); - Path path2 = Paths.get(userHome, nomeAleatorio + "-copia.txt"); + Path path1 = Paths.get(userHome, randomName); + Path path2 = Paths.get(userHome, randomName + "-copy.txt"); System.out.println("Path 1: " + path1); System.out.println("Path 2: " + path2); try { - System.out.println("Path 1 existe? " + Files.exists(path1)); + System.out.println("Path 1 exist? " + Files.exists(path1)); Files.createFile(path1); - System.out.println("Path 1 existe? " + Files.exists(path1)); - System.out.println("Path 2 existe? " + Files.exists(path2)); + System.out.println("Path 1 exist? " + Files.exists(path1)); + System.out.println("Path 2 exist? " + Files.exists(path2)); Files.copy(path1, path2); - System.out.println("Path 2 existe? " + Files.exists(path2)); + System.out.println("Path 2 exist? " + Files.exists(path2)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CopyToPath.java b/src/org/j6toj8/fileio/files/Files_CopyToPath.java index c584790..f6cab8e 100644 --- a/src/org/j6toj8/fileio/files/Files_CopyToPath.java +++ b/src/org/j6toj8/fileio/files/Files_CopyToPath.java @@ -15,15 +15,14 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "copia" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "copy" + new Random().nextInt() + ".txt"; - try (FileInputStream fis = new FileInputStream(userHome + File.separator + "arquivo1.txt")) { - Path pathParaCopia = Paths.get(userHome, nomeAleatorio); - System.out.println("Path 2 existe? " + Files.exists(pathParaCopia)); - Files.copy(fis, pathParaCopia); - System.out.println("Path 2 existe? " + Files.exists(pathParaCopia)); + try (FileInputStream fis = new FileInputStream(userHome + File.separator + "file1.txt")) { + Path pathToCopy = Paths.get(userHome, randomName); + System.out.println("Path 2 exist? " + Files.exists(pathToCopy)); + Files.copy(fis, pathToCopy); + System.out.println("Path 2 exist? " + Files.exists(pathToCopy)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CreateDirectories.java b/src/org/j6toj8/fileio/files/Files_CreateDirectories.java index 7bacb39..714c72b 100644 --- a/src/org/j6toj8/fileio/files/Files_CreateDirectories.java +++ b/src/org/j6toj8/fileio/files/Files_CreateDirectories.java @@ -13,25 +13,24 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de diretório, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio1 = "arquivo" + new Random().nextInt(); - String nomeAleatorio2 = "arquivo" + new Random().nextInt(); - String nomeAleatorio3 = "arquivo" + new Random().nextInt(); + // Using a random directory name, just for example to run countless times without problems + String randomName1 = "file" + new Random().nextInt(); + String randomName2 = "file" + new Random().nextInt(); + String randomName3 = "file" + new Random().nextInt(); - Path path = Paths.get(userHome, nomeAleatorio1, nomeAleatorio2, nomeAleatorio3); + Path path = Paths.get(userHome, randomName1, randomName2, randomName3); System.out.println("Path: " + path); try { - Files.createDirectory(path); // MÉTODO ERRADO, LANÇA EXCEÇÃO + Files.createDirectory(path); // WRONG METHOD, THROWS EXCEPTION } catch (IOException e) { e.printStackTrace(); } try { - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); Files.createDirectories(path); - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CreateDirectory.java b/src/org/j6toj8/fileio/files/Files_CreateDirectory.java index 0fb8266..594af90 100644 --- a/src/org/j6toj8/fileio/files/Files_CreateDirectory.java +++ b/src/org/j6toj8/fileio/files/Files_CreateDirectory.java @@ -13,17 +13,16 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de diretório, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt(); + // Using a random directory name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt(); - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); Files.createDirectory(path); - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_CreateFile.java b/src/org/j6toj8/fileio/files/Files_CreateFile.java index 90bed8b..8e83247 100644 --- a/src/org/j6toj8/fileio/files/Files_CreateFile.java +++ b/src/org/j6toj8/fileio/files/Files_CreateFile.java @@ -13,17 +13,16 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); Files.createFile(path); - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_DeletePath.java b/src/org/j6toj8/fileio/files/Files_DeletePath.java index bd5288e..cf6f548 100644 --- a/src/org/j6toj8/fileio/files/Files_DeletePath.java +++ b/src/org/j6toj8/fileio/files/Files_DeletePath.java @@ -13,23 +13,22 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); Files.createFile(path); - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); - Files.delete(path); // tenta apagadar o Path e lança exceção se ele não existir - System.out.println("Path existe? " + Files.exists(path)); + Files.delete(path); // try to delete Path and throw exception if it doesn't exist + System.out.println("Path exist? " + Files.exists(path)); - Files.deleteIfExists(path); // tenta apagadar o Path e não faz nada se ele não existir - System.out.println("Path existe? " + Files.exists(path)); + Files.deleteIfExists(path); // try to delete the Path and do nothing if it doesn't exist + System.out.println("Path exist? " + Files.exists(path)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_LastModified.java b/src/org/j6toj8/fileio/files/Files_LastModified.java index c922f4d..47c6931 100644 --- a/src/org/j6toj8/fileio/files/Files_LastModified.java +++ b/src/org/j6toj8/fileio/files/Files_LastModified.java @@ -15,19 +15,18 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { Files.createFile(path); - System.out.println("Data de Modificação: " + Files.getLastModifiedTime(path)); + System.out.println("Date Modified: " + Files.getLastModifiedTime(path)); FileTime fileTime = FileTime.from(Instant.now().plusMillis(10000)); Files.setLastModifiedTime(path, fileTime); - System.out.println("Data de Modificação: " + Files.getLastModifiedTime(path)); + System.out.println("Date Modified: " + Files.getLastModifiedTime(path)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_MoveFile.java b/src/org/j6toj8/fileio/files/Files_MoveFile.java index bfadf99..7c0b610 100644 --- a/src/org/j6toj8/fileio/files/Files_MoveFile.java +++ b/src/org/j6toj8/fileio/files/Files_MoveFile.java @@ -13,22 +13,22 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + String randomName = "arquivo" + new Random().nextInt() + ".txt"; - Path arquivoOrigem = Paths.get(userHome, nomeAleatorio); - Path arquivoDestino = Paths.get(userHome, nomeAleatorio + "-movido.txt"); - System.out.println("Path Arquivo Origem: " + arquivoOrigem); - System.out.println("Path Arquivo Destino: " + arquivoDestino); + Path sourceFile = Paths.get(userHome, randomName); + Path destinationFile = Paths.get(userHome, randomName + "-moved.txt"); + System.out.println("Path Source File: " + sourceFile); + System.out.println("Path Destination File: " + destinationFile); try { - System.out.println("Arquivo origem existe? " + Files.exists(arquivoOrigem)); - Files.createFile(arquivoOrigem); - System.out.println("Arquivo origem existe? " + Files.exists(arquivoOrigem)); + System.out.println("Source File exist? " + Files.exists(sourceFile)); + Files.createFile(sourceFile); + System.out.println("Source File exist? " + Files.exists(sourceFile)); - System.out.println("Arquivo destino existe? " + Files.exists(arquivoDestino)); - Files.move(arquivoOrigem, arquivoDestino); - System.out.println("Arquivo destino existe? " + Files.exists(arquivoDestino)); - System.out.println("Arquivo origem existe? " + Files.exists(arquivoOrigem)); + System.out.println("Destination File exist? " + Files.exists(destinationFile)); + Files.move(sourceFile, destinationFile); + System.out.println("Destination File exist? " + Files.exists(destinationFile)); + System.out.println("Source File exist? " + Files.exists(sourceFile)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_Owner.java b/src/org/j6toj8/fileio/files/Files_Owner.java index b6e4931..73d5fb1 100644 --- a/src/org/j6toj8/fileio/files/Files_Owner.java +++ b/src/org/j6toj8/fileio/files/Files_Owner.java @@ -16,23 +16,22 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { Files.createFile(path); - System.out.println(Files.getOwner(path)); // imprime o owner atual - - // Pega o serviço do sistema para buscar um usuário + System.out.println(Files.getOwner(path)); // print the current owner + + // Get system service to fetch a user UserPrincipalLookupService service = FileSystems.getDefault().getUserPrincipalLookupService(); - // Busca pelo usuário com nome 'rinaldo' + // Search for user with name 'rinaldo' UserPrincipal userPrincipal = service.lookupPrincipalByName("rinaldo"); - Files.setOwner(path, userPrincipal); // altera o owner + Files.setOwner(path, userPrincipal); // change owner System.out.println(Files.getOwner(path)); } catch (IOException e) { e.printStackTrace(); diff --git a/src/org/j6toj8/fileio/files/Files_ReadAllLines.java b/src/org/j6toj8/fileio/files/Files_ReadAllLines.java index 313252d..0ccaece 100644 --- a/src/org/j6toj8/fileio/files/Files_ReadAllLines.java +++ b/src/org/j6toj8/fileio/files/Files_ReadAllLines.java @@ -13,10 +13,10 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivo.txt"); + Path path = Paths.get(userHome, "file.txt"); try { - List conteudo = Files.readAllLines(path); - System.out.println(conteudo); + List content = Files.readAllLines(path); + System.out.println(content); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_SameFile.java b/src/org/j6toj8/fileio/files/Files_SameFile.java index 416b149..5b4d7ad 100644 --- a/src/org/j6toj8/fileio/files/Files_SameFile.java +++ b/src/org/j6toj8/fileio/files/Files_SameFile.java @@ -12,17 +12,17 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path1 = Paths.get(userHome, "arquivo1.txt"); - Path path2 = Paths.get("/", "home", "rinaldo", "arquivo1.txt"); - Path path3 = Paths.get("/home/rinaldo/arquivo1.txt"); - Path path4 = Paths.get("/home/rinaldo/Downloads/../arquivo1.txt"); + Path path1 = Paths.get(userHome, "file1.txt"); + Path path2 = Paths.get("/", "home", "rinaldo", "file1.txt"); + Path path3 = Paths.get("/home/rinaldo/file1.txt"); + Path path4 = Paths.get("/home/rinaldo/Downloads/../file1.txt"); try { - // todos os Path são iguais - System.out.println("Path 1 e Path 2 são iguais? " + Files.isSameFile(path1, path2)); - System.out.println("Path 2 e Path 3 são iguais? " + Files.isSameFile(path2, path3)); - System.out.println("Path 3 e Path 4 são iguais? " + Files.isSameFile(path3, path4)); - System.out.println("Path 1 e Path 4 são iguais? " + Files.isSameFile(path1, path4)); + // all Paths are equal + System.out.println("Are Path 1 and Path 2 the same? " + Files.isSameFile(path1, path2)); + System.out.println("Are Path 2 and Path 3 the same? " + Files.isSameFile(path2, path3)); + System.out.println("Are Path 3 and Path 4 the same? " + Files.isSameFile(path3, path4)); + System.out.println("Are Path 1 and Path 4 the same? " + Files.isSameFile(path1, path4)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/files/Files_WriteFile.java b/src/org/j6toj8/fileio/files/Files_WriteFile.java index 8c36427..8d3c1ab 100644 --- a/src/org/j6toj8/fileio/files/Files_WriteFile.java +++ b/src/org/j6toj8/fileio/files/Files_WriteFile.java @@ -15,22 +15,20 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // Utilizando um nome aleatório de arquivo, - // apenas para o exemplo executar inúmeras vezes sem problemas - String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; + // Using a random file name, just for example to run countless times without problems + String randomName = "file" + new Random().nextInt() + ".txt"; - Path path = Paths.get(userHome, nomeAleatorio); + Path path = Paths.get(userHome, randomName); System.out.println("Path: " + path); try { - System.out.println("Path existe? " + Files.exists(path)); - Files.createFile(path); // cria o arquivo - System.out.println("Path existe? " + Files.exists(path)); + System.out.println("Path exist? " + Files.exists(path)); + Files.createFile(path); + System.out.println("Path exist? " + Files.exists(path)); } catch (IOException e1) { e1.printStackTrace(); } try (BufferedWriter bw = Files.newBufferedWriter(path)) { - // escreve no arquivo bw.write("1"); bw.write("2"); bw.write("3"); @@ -39,8 +37,7 @@ public static void main(String[] args) { } try (BufferedReader br = Files.newBufferedReader(path)) { - // lê as linhas do arquivo - String line = br.readLine(); + String line = br.readLine(); do { System.out.println(line); } while (br.readLine() != null); diff --git a/src/org/j6toj8/fileio/paths/Paths_Creation.java b/src/org/j6toj8/fileio/paths/Paths_Creation.java index 41e004c..e0371a1 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Creation.java +++ b/src/org/j6toj8/fileio/paths/Paths_Creation.java @@ -9,47 +9,47 @@ public class Paths_Creation { public static void main(String[] args) { // tag::code[] - // diretório padrão do usuário + // default user directory String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - // path absoluto + // absolute path Path path1 = Paths.get("/home/rinaldo"); System.out.println("Path 1: " + path1); - // path absoluto dividido em strings + // absolute path divided into strings Path path2 = Paths.get("/", "home", "rinaldo"); System.out.println("Path 2: " + path2); - // path absoluto a partir do userHome + // absolute path from userHome Path path3 = Paths.get(userHome); System.out.println("Path 3: " + path3); - // path absoluto para um arquivo + // absolute path to a file Path path4 = Paths.get("/home/rinaldo/arquivos/arquivo.txt"); System.out.println("Path 4: " + path4); - // path absoluto para um arquivo a partir do userHome + // absolute path to a file from userHome Path path5 = Paths.get(userHome, "arquivos", "arquivo.txt"); System.out.println("Path 5: " + path5); - // path absoluto em um sistema windows + // absolute path on a windows system Path path6 = Paths.get("C:/users/rinaldo"); System.out.println("Path 6: " + path6); - // path absoluto windows divido em strings + // absolute path on a windows split into strings Path path7 = Paths.get("C:", "users", "rinaldo"); System.out.println("Path 7: " + path7); - // path relativo + // relative path Path path8 = Paths.get("rinaldo"); System.out.println("Path 8: " + path8); - // path a partir de uma URI + // path from a URI Path path9 = Paths.get(URI.create("file:///home/rinaldo/arquivos/arquivo.txt")); System.out.println("Path 9: " + path9); - - // path sem utilizar a classe Paths - produz o mesmo resultado + + // path without using the Paths class - produces the same result Path path10 = FileSystems.getDefault().getPath("/home/rinaldo"); System.out.println("Path 10: " + path10); // end::code[] diff --git a/src/org/j6toj8/fileio/paths/Paths_CreationDoesntExists.java b/src/org/j6toj8/fileio/paths/Paths_CreationDoesntExists.java index 4d985c0..074ba48 100644 --- a/src/org/j6toj8/fileio/paths/Paths_CreationDoesntExists.java +++ b/src/org/j6toj8/fileio/paths/Paths_CreationDoesntExists.java @@ -10,7 +10,7 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivoQueNaoExiste.txt"); + Path path = Paths.get(userHome, "fileThatDoesNotExist.txt"); System.out.println("Path: " + path); // end::code[] } diff --git a/src/org/j6toj8/fileio/paths/Paths_Information.java b/src/org/j6toj8/fileio/paths/Paths_Information.java index 9bffec0..3731abd 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Information.java +++ b/src/org/j6toj8/fileio/paths/Paths_Information.java @@ -10,21 +10,21 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome + "\n"); - Path path1 = Paths.get(userHome, "arquivos", "arquivo.txt"); // absoluto - System.out.println("Representação em String: " + path1.toString()); - System.out.println("Nome do Arquivo: " + path1.getFileName()); - System.out.println("Diretório Superior: " + path1.getParent()); - System.out.println("Diretório Raiz: " + path1.getRoot()); - System.out.println("É absoluto?: " + path1.isAbsolute()); + Path path1 = Paths.get(userHome, "files", "file.txt"); // absolute + System.out.println("String representation: " + path1.toString()); + System.out.println("File Name: " + path1.getFileName()); + System.out.println("Top Directory: " + path1.getParent()); + System.out.println("Root Directory: " + path1.getRoot()); + System.out.println("Is it absolute?: " + path1.isAbsolute()); System.out.println(); - Path path2 = Paths.get("home", "rinaldo", "arquivos"); // relativo - System.out.println("Representação em String: " + path2.toString()); - System.out.println("Nome do Arquivo: " + path2.getFileName()); - System.out.println("Diretório Superior: " + path2.getParent()); - System.out.println("Diretório Raiz: " + path2.getRoot()); - System.out.println("É absoluto?: " + path2.isAbsolute()); + Path path2 = Paths.get("home", "rinaldo", "files"); // relative + System.out.println("String representation: " + path2.toString()); + System.out.println("File Name: " + path2.getFileName()); + System.out.println("Top Directory: " + path2.getParent()); + System.out.println("Root Directory: " + path2.getRoot()); + System.out.println("Is it absolute?: " + path2.isAbsolute()); // end::code[] } diff --git a/src/org/j6toj8/fileio/paths/Paths_Names.java b/src/org/j6toj8/fileio/paths/Paths_Names.java index 00da14c..ffa2c87 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Names.java +++ b/src/org/j6toj8/fileio/paths/Paths_Names.java @@ -10,10 +10,10 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome + "\n"); - Path path = Paths.get(userHome, "arquivos", "arquivo.txt"); - int nameCount = path.getNameCount(); // quantidade de elementos no Path + Path path = Paths.get(userHome, "files", "file.txt"); + int nameCount = path.getNameCount(); // number of elements in Path for (int i = 0; i < nameCount; i++) { - Path name = path.getName(i);// recupera o elemento específico + Path name = path.getName(i);// retrieve the specific element System.out.println(name); } // end::code[] diff --git a/src/org/j6toj8/fileio/paths/Paths_Normalize.java b/src/org/j6toj8/fileio/paths/Paths_Normalize.java index e6b0801..e1e74d3 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Normalize.java +++ b/src/org/j6toj8/fileio/paths/Paths_Normalize.java @@ -12,13 +12,13 @@ public static void main(String[] args) { System.out.println(); - Path path1 = Paths.get(userHome, "arquivos/./arquivo1.txt"); + Path path1 = Paths.get(userHome, "files/./file1.txt"); System.out.println("Path: " + path1); System.out.println("Path normalize: " + path1.normalize()); System.out.println(); - Path path2 = Paths.get(userHome, "arquivos/../arquivo1.txt"); + Path path2 = Paths.get(userHome, "files/../file1.txt"); System.out.println("Path: " + path2); System.out.println("Path normalize: " + path2.normalize()); diff --git a/src/org/j6toj8/fileio/paths/Paths_Relativize.java b/src/org/j6toj8/fileio/paths/Paths_Relativize.java index c35d98b..2689c08 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Relativize.java +++ b/src/org/j6toj8/fileio/paths/Paths_Relativize.java @@ -12,32 +12,32 @@ public static void main(String[] args) { System.out.println(); - Path pathAbsoluto1 = Paths.get(userHome, "arquivos"); - Path pathAbsoluto2 = Paths.get(userHome, "arquivos/arquivo1.txt"); - System.out.println("Absoluto 1: " + pathAbsoluto1); - System.out.println("Absoluto 2: " + pathAbsoluto2); + Path pathAbsolute1 = Paths.get(userHome, "files"); + Path pathAbsolute2 = Paths.get(userHome, "files/file1.txt"); + System.out.println("Absolute 1: " + pathAbsolute1); + System.out.println("Absolute 2: " + pathAbsolute2); - Path pathRelativo1 = Paths.get("arquivo1.txt"); - Path pathRelativo2 = Paths.get("arquivos/arquivo1.txt"); - System.out.println("Relativo 1: " + pathRelativo1); - System.out.println("Relativo 2: " + pathRelativo2); + Path pathRelative1 = Paths.get("file1.txt"); + Path pathRelative2 = Paths.get("files/file1.txt"); + System.out.println("Relative 1: " + pathRelative1); + System.out.println("Relative 2: " + pathRelative2); - System.out.println("Absoluto 1 + Absoluto 2: " + pathAbsoluto1.relativize(pathAbsoluto2)); - System.out.println("Absoluto 2 + Absoluto 1: " + pathAbsoluto2.relativize(pathAbsoluto1)); + System.out.println("Absolute 1 + Absolute 2: " + pathAbsolute1.relativize(pathAbsolute2)); + System.out.println("Absolute 2 + Absolute 1: " + pathAbsolute2.relativize(pathAbsolute1)); - System.out.println("Relativo 1 + Relativo 2: " + pathRelativo1.relativize(pathRelativo2)); - System.out.println("Relativo 2 + Relativo 1: " + pathRelativo2.relativize(pathRelativo1)); + System.out.println("Relative 1 + Relative 2: " + pathRelative1.relativize(pathRelative2)); + System.out.println("Relative 2 + Relative 1: " + pathRelative2.relativize(pathRelative1)); try { - // Exceção será lançada, pois não é possível chamar relativize em tipos diferente de Path - System.out.println("Absoluto + Relativo: " + pathAbsoluto1.relativize(pathRelativo1)); + // Exception will be thrown as it is not possible to call relativize on types other than Path + System.out.println("Absolute + Relative: " + pathAbsolute1.relativize(pathRelative1)); } catch (Exception e) { e.printStackTrace(); } try { - // Exceção será lançada, pois não é possível chamar relativize em tipos diferente de Path - System.out.println("Relativo + Absoluto: " + pathRelativo1.relativize(pathAbsoluto1)); + // Exception will be thrown as it is not possible to call relativize on types other than Path + System.out.println("Relative + Absolute: " + pathRelative1.relativize(pathAbsolute1)); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/paths/Paths_Resolve.java b/src/org/j6toj8/fileio/paths/Paths_Resolve.java index bd0f978..abf5f35 100644 --- a/src/org/j6toj8/fileio/paths/Paths_Resolve.java +++ b/src/org/j6toj8/fileio/paths/Paths_Resolve.java @@ -12,12 +12,12 @@ public static void main(String[] args) { System.out.println(); - Path path1 = Paths.get(userHome, "arquivos"); - Path path2 = Paths.get("arquivo1.txt"); - System.out.println("Absoluto + Relativo: " + path1.resolve(path2)); - System.out.println("Relativo + Absoluto: " + path2.resolve(path1)); - System.out.println("Absoluto + Absoluto: " + path1.resolve(path1)); - System.out.println("Relativo + Relativo: " + path2.resolve(path2)); + Path path1 = Paths.get(userHome, "files"); + Path path2 = Paths.get("file1.txt"); + System.out.println("Absolute + Relative: " + path1.resolve(path2)); + System.out.println("Relative + Absolute: " + path2.resolve(path1)); + System.out.println("Absolute + Absolute: " + path1.resolve(path1)); + System.out.println("Relative + Relative: " + path2.resolve(path2)); // end::code[] } diff --git a/src/org/j6toj8/fileio/paths/Paths_SubPath.java b/src/org/j6toj8/fileio/paths/Paths_SubPath.java index c001d51..f5bed2c 100644 --- a/src/org/j6toj8/fileio/paths/Paths_SubPath.java +++ b/src/org/j6toj8/fileio/paths/Paths_SubPath.java @@ -10,7 +10,7 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivos", "arquivo1.txt"); + Path path = Paths.get(userHome, "files", "file1.txt"); System.out.println("Path: " + path); Path subpath1 = path.subpath(0, 1); @@ -25,7 +25,7 @@ public static void main(String[] args) { Path subpath4 = path.subpath(2, 4); System.out.println(subpath4); - Path subpath5 = path.subpath(3, 5); // EXCEÇÃO, pois só existem 4 elementos no path + Path subpath5 = path.subpath(3, 5); // EXCEPTION, as there are only 4 elements in path // end::code[] } diff --git a/src/org/j6toj8/fileio/paths/Paths_ToAbsolute.java b/src/org/j6toj8/fileio/paths/Paths_ToAbsolute.java index 363aa49..52187b3 100644 --- a/src/org/j6toj8/fileio/paths/Paths_ToAbsolute.java +++ b/src/org/j6toj8/fileio/paths/Paths_ToAbsolute.java @@ -7,15 +7,15 @@ public class Paths_ToAbsolute { public static void main(String[] args) { // tag::code[] - Path path = Paths.get("arquivos"); + Path path = Paths.get("files"); System.out.println(path); - System.out.println("É absoluto? " + path.isAbsolute()); + System.out.println("Is it absolute? " + path.isAbsolute()); System.out.println(); Path absolutePath = path.toAbsolutePath(); System.out.println(absolutePath); - System.out.println("É absoluto? " + absolutePath.isAbsolute()); + System.out.println("Is it absolute? " + absolutePath.isAbsolute()); // end::code[] } diff --git a/src/org/j6toj8/fileio/paths/Paths_ToFile.java b/src/org/j6toj8/fileio/paths/Paths_ToFile.java index 573dc6d..863f7c8 100644 --- a/src/org/j6toj8/fileio/paths/Paths_ToFile.java +++ b/src/org/j6toj8/fileio/paths/Paths_ToFile.java @@ -11,7 +11,7 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path path = Paths.get(userHome, "arquivoQueNaoExiste.txt"); + Path path = Paths.get(userHome, "fileThatDoesNotExist.txt"); System.out.println("Path: " + path); File file = path.toFile(); diff --git a/src/org/j6toj8/fileio/paths/Paths_ToRealPath.java b/src/org/j6toj8/fileio/paths/Paths_ToRealPath.java index 2dbe249..7e81f0f 100644 --- a/src/org/j6toj8/fileio/paths/Paths_ToRealPath.java +++ b/src/org/j6toj8/fileio/paths/Paths_ToRealPath.java @@ -11,18 +11,18 @@ public static void main(String[] args) { String userHome = System.getProperty("user.home"); System.out.println("User home: " + userHome); - Path pathQueExiste = Paths.get(userHome, "arquivo1.txt"); - Path pathQueNaoExiste = Paths.get(userHome, "arquivoQueNaoExiste.txt"); + Path pathThatDoesExist = Paths.get(userHome, "file1.txt"); + Path pathThatDoesNotExist = Paths.get(userHome, "fileThatDoesNotExist.txt"); try { - Path realPath = pathQueExiste.toRealPath(); + Path realPath = pathThatDoesExist.toRealPath(); System.out.println("realPath: " + realPath); } catch (IOException e) { e.printStackTrace(); } try { - pathQueNaoExiste.toRealPath(); // LANÇA EXCEÇÃO + pathThatDoesNotExist.toRealPath(); // THROWS EXCEPTION } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_DirectoryStream.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_DirectoryStream.java index f0fe010..81f128a 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_DirectoryStream.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_DirectoryStream.java @@ -11,11 +11,11 @@ public class Recursive_DirectoryStream { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try (DirectoryStream directoryStream = Files.newDirectoryStream(path)) { - // iteração com sintaxe for-each + // iteration with for-each syntax for (Path subPath : directoryStream) { System.out.println(subPath); } @@ -24,7 +24,7 @@ public static void main(String[] args) { } try (DirectoryStream directoryStream = Files.newDirectoryStream(path)) { - // iteração com operação forEach e expressão lambda + // iteration with forEach operation and lambda expression directoryStream.forEach(p -> System.out.println(p)); } catch (IOException e) { e.printStackTrace(); diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_FileVisitor.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_FileVisitor.java index 32160b7..94992db 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_FileVisitor.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_FileVisitor.java @@ -11,38 +11,38 @@ public class Recursive_FileVisitor { // tag::code[] - static class MeuFileVisitor implements FileVisitor { + static class MyFileVisitor implements FileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - System.out.println("Arquivo visitado: " + file); + System.out.println("Visited file: " + file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - System.out.println("Antes de visitar o diretório: " + dir); + System.out.println("Before visiting the directory: " + dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - System.out.println("Após de visitar o diretório: " + dir); + System.out.println("After visiting the directory: " + dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { - System.out.println("Falhou ao visitar o arquivo: " + file); + System.out.println("Failed to visit file: " + file); return FileVisitResult.CONTINUE; } } public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - Files.walkFileTree(path, new MeuFileVisitor()); + Files.walkFileTree(path, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_SimpleFileVisitor.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_SimpleFileVisitor.java index b3dca57..8b6725f 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_SimpleFileVisitor.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_SimpleFileVisitor.java @@ -11,24 +11,23 @@ public class Recursive_SimpleFileVisitor { // tag::code[] - // Implementação simples de um SimpleFileVisitor - static class MeuFileVisitor extends SimpleFileVisitor { + // Simple Implementation of a SimpleFileVisitor + static class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - // Método que será invocado a cada arquivo encontrado - System.out.println("Arquivo visitado: " + file + ". Tamanho: " + attrs.size()); - return FileVisitResult.CONTINUE; // instrui o FileVisitor a continuar seguindo a árvore de arquivos + // Method that will be invoked for each file found + System.out.println("Visited file: " + file + ". Size: " + attrs.size()); + return FileVisitResult.CONTINUE; // instructs FileVisitor to continue following the file tree } } public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - // Utilização da classe MeuFileVisitor para acessar - // todos os arquivos no diretório e seus subdiretórios - Files.walkFileTree(path, new MeuFileVisitor()); + // Using the MyFileVisitor class to access all files in the directory and their subdirectories. + Files.walkFileTree(path, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorDirectory.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorDirectory.java index 0aecc02..7d551a1 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorDirectory.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorDirectory.java @@ -11,25 +11,25 @@ public class Recursive_VisitorDirectory { // tag::code[] - static class MeuFileVisitor extends SimpleFileVisitor { + static class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - System.out.println("Arquivo visitado: " + file + ". Tamanho: " + attrs.size()); + System.out.println("Visited file: " + file + ". Size: " + attrs.size()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - // Ação que será executada antes de visitar um diretório - if (dir.getFileName().toString().equals("subpasta12")) { - return FileVisitResult.SKIP_SUBTREE; // ignora o diretório subpasta12 + // Action that will be performed before visiting a directory + if (dir.getFileName().toString().equals("subfolder12")) { + return FileVisitResult.SKIP_SUBTREE; // ignore directory subfolder12 } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - // Ação que será executada depois de visitar um diretório + // Action that will be performed after visiting a directory return FileVisitResult.CONTINUE; } @@ -37,10 +37,10 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOEx public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - Files.walkFileTree(path, new MeuFileVisitor()); + Files.walkFileTree(path, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorIgnoreSiblings.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorIgnoreSiblings.java index bce3f4a..6fd14d2 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorIgnoreSiblings.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorIgnoreSiblings.java @@ -11,13 +11,12 @@ public class Recursive_VisitorIgnoreSiblings { // tag::code[] - static class MeuFileVisitor extends SimpleFileVisitor { + static class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - System.out.println("Arquivo visitado: " + file + ". Tamanho: " + attrs.size()); - if (file.getFileName().toString().equals("arquivo11.txt")) { - // ao encontrar o arquivo11.txt irá parar de visitar qualquer - // diretório ou arquivo que seja "irmão" (que está lado a lado) + System.out.println("Visited file: " + file + ". Size: " + attrs.size()); + if (file.getFileName().toString().equals("file11.txt")) { + // finding file11.txt will stop visiting any directory or file that is "sibling" (which is side by side) return FileVisitResult.SKIP_SIBLINGS; } return FileVisitResult.CONTINUE; @@ -26,10 +25,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - Files.walkFileTree(path, new MeuFileVisitor()); + Files.walkFileTree(path, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorOptionsAndDepth.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorOptionsAndDepth.java index 0a6a09a..ad687d7 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorOptionsAndDepth.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorOptionsAndDepth.java @@ -13,25 +13,24 @@ public class Recursive_VisitorOptionsAndDepth { // tag::code[] - static class MeuFileVisitor extends SimpleFileVisitor { + static class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - System.out.println("Arquivo visitado: " + file); + System.out.println("Visited file: " + file); return FileVisitResult.CONTINUE; } } public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { HashSet opcoes = new HashSet(); opcoes.add(FileVisitOption.FOLLOW_LINKS); - - // visita a árvore com limite de profundidade 2 - // e com a opção de também visitar links simbólicos - Files.walkFileTree(path, opcoes, 2, new MeuFileVisitor()); + + // visit tree with depth limit 2 and option to also visit symbolic links + Files.walkFileTree(path, opcoes, 2, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorTerminate.java b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorTerminate.java index 20420a4..4d9f8da 100644 --- a/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorTerminate.java +++ b/src/org/j6toj8/fileio/recursiveaccess/Recursive_VisitorTerminate.java @@ -11,13 +11,13 @@ public class Recursive_VisitorTerminate { // tag::code[] - static class MeuFileVisitor extends SimpleFileVisitor { + static class MyFileVisitor extends SimpleFileVisitor { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - System.out.println("Arquivo visitado: " + file + ". Tamanho: " + attrs.size()); - if (file.getFileName().toString().equals("arquivo122.txt")) { - System.out.println("Arquivo encontrado. Finalizando."); - return FileVisitResult.TERMINATE; // finaliza o acesso à árvore de arquivos + System.out.println("Visited file: " + file + ". Size: " + attrs.size()); + if (file.getFileName().toString().equals("file122.txt")) { + System.out.println("File found. Terminating."); + return FileVisitResult.TERMINATE; // terminates file tree access } return FileVisitResult.CONTINUE; } @@ -25,10 +25,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO public static void main(String[] args) { String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try { - Files.walkFileTree(path, new MeuFileVisitor()); + Files.walkFileTree(path, new MyFileVisitor()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/watchservice/WatchService_CreateDelete.java b/src/org/j6toj8/fileio/watchservice/WatchService_CreateDelete.java index a1a0624..8f553e1 100644 --- a/src/org/j6toj8/fileio/watchservice/WatchService_CreateDelete.java +++ b/src/org/j6toj8/fileio/watchservice/WatchService_CreateDelete.java @@ -15,25 +15,25 @@ public class WatchService_CreateDelete { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); - // criação do WatchService - ainda sem monitorar nada + // WatchService creation - still not monitoring anything try (WatchService service = FileSystems.getDefault().newWatchService();) { - - // registro do WatchService no Path para monitorar os evento de CREATE e DELETE + + // WatchService log in Path to monitor CREATE and DELETE events path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); - while (true) { // loop infinito - // take() irá retornar sempre que houverem eventos - // caso contrário a chamada fica parada esperando eventos ocorrerem + while (true) { // infinite loop + // take() will return whenever there are events + // otherwise the call is stopped waiting for events to occur WatchKey key = service.take(); - List> pollEvents = key.pollEvents(); // recupera os eventos ocorridos - System.out.println("Eventos capturados. Quantidade: " + pollEvents.size()); - for (WatchEvent event : pollEvents) { // iteração sobre todos os eventos recuperados - System.out.println("Evento ocorrido. Tipo : " + event.kind() + ". Contexto: " + event.context()); + List> pollEvents = key.pollEvents(); // recovers events + System.out.println("Events captured. Quantity: " + pollEvents.size()); + for (WatchEvent event : pollEvents) { // iteration over all retrieved events + System.out.println("Event occurred. Type: " + event.kind() + ". Context: " + event.context()); } - key.reset(); // reseta o WatchKey para que possa ser utilizado novamente + key.reset(); // resets WatchKey so that it can be used again } } catch (IOException | InterruptedException e) { e.printStackTrace(); diff --git a/src/org/j6toj8/fileio/watchservice/WatchService_File.java b/src/org/j6toj8/fileio/watchservice/WatchService_File.java index 55d681b..40842d4 100644 --- a/src/org/j6toj8/fileio/watchservice/WatchService_File.java +++ b/src/org/j6toj8/fileio/watchservice/WatchService_File.java @@ -12,11 +12,11 @@ public class WatchService_File { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos", "arquivo1.txt"); // NÃO SUPORTADO + Path path = Paths.get(userHome, "files", "file1.txt"); // NOT SUPPORTED System.out.println("Path: " + path); try (WatchService service = FileSystems.getDefault().newWatchService();) { - path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); // LANÇA EXCEÇÃO + path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); // THROWS EXCEPTION } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/fileio/watchservice/WatchService_Modify.java b/src/org/j6toj8/fileio/watchservice/WatchService_Modify.java index 341fcc1..7f6d541 100644 --- a/src/org/j6toj8/fileio/watchservice/WatchService_Modify.java +++ b/src/org/j6toj8/fileio/watchservice/WatchService_Modify.java @@ -15,25 +15,25 @@ public class WatchService_Modify { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); - // criação do WatchService - ainda sem monitorar nada + // WatchService creation - still not monitoring anything try (WatchService service = FileSystems.getDefault().newWatchService();) { - - // registro do WatchService no Path para monitorar o evento de MODIFY + + // WatchService log in Path to monitor MODIFY event path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); - - while (true) { // loop infinito - // take() irá retornar sempre que houverem eventos - // caso contrário a chamada fica parada esperando eventos ocorrerem + + while (true) { // infinite loop + // take() will return whenever there are events + // otherwise the call is stopped waiting for events to occur WatchKey key = service.take(); - List> pollEvents = key.pollEvents(); // recupera os eventos ocorridos - System.out.println("Eventos capturados. Quantidade: " + pollEvents.size()); - for (WatchEvent event : pollEvents) { // iteração sobre todos os eventos recuperados - System.out.println("Evento ocorrido. Tipo : " + event.kind() + ". Contexto: " + event.context()); + List> pollEvents = key.pollEvents(); // recovers events + System.out.println("Events captured. Quantity: " + pollEvents.size()); + for (WatchEvent event : pollEvents) { // iteration over all retrieved events + System.out.println("Event occurred. Type: " + event.kind() + ". Context: " + event.context()); } - key.reset(); // reseta o WatchKey para que possa ser utilizado novamente + key.reset(); // resets WatchKey so that it can be used again } } catch (IOException | InterruptedException e) { e.printStackTrace(); diff --git a/src/org/j6toj8/fileio/watchservice/WatchService_Poll.java b/src/org/j6toj8/fileio/watchservice/WatchService_Poll.java index 8bcc437..7b98ce3 100644 --- a/src/org/j6toj8/fileio/watchservice/WatchService_Poll.java +++ b/src/org/j6toj8/fileio/watchservice/WatchService_Poll.java @@ -15,21 +15,21 @@ public class WatchService_Poll { public static void main(String[] args) { // tag::code[] String userHome = System.getProperty("user.home"); - Path path = Paths.get(userHome, "arquivos"); + Path path = Paths.get(userHome, "files"); System.out.println("Path: " + path); try (WatchService service = FileSystems.getDefault().newWatchService();) { path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); - System.out.println("Horário antes do poll sem timeout: " + LocalTime.now()); - WatchKey key1 = service.poll(); // retorna imediatamente, mesmo que não haja evento - System.out.println("WatchKey do poll: " + key1); - System.out.println("Horário depois do poll sem timeout: " + LocalTime.now()); + System.out.println("Time before poll without timeout: " + LocalTime.now()); + WatchKey key1 = service.poll(); // returns immediately even if there is no event + System.out.println("WatchKey's poll: " + key1); + System.out.println("Time after poll without timeout: " + LocalTime.now()); - System.out.println("Horário antes do poll com timeout: " + LocalTime.now()); - WatchKey key2 = service.poll(5, TimeUnit.SECONDS); // retorna após 5 segundos, mesmo que não haja evento - System.out.println("WatchKey do poll com timeout: " + key2); - System.out.println("Horário depois do poll com timeout: " + LocalTime.now()); + System.out.println("Time before poll with timeout: " + LocalTime.now()); + WatchKey key2 = service.poll(5, TimeUnit.SECONDS); // returns after 5 seconds even if there is no event + System.out.println("WatchKey's poll with timeout: " + key2); + System.out.println("Time after poll with timeout: " + LocalTime.now()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerExample.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerExample.java index 9263e6e..75ce412 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerExample.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerExample.java @@ -9,11 +9,11 @@ public class BuiltInInterfaces_ConsumerExample { // tag::code[] public static void main(String[] args) { - Consumer impressor = x -> System.out.println(x); - impressor.accept(LocalDate.now()); // imprimirá a data atual + Consumer printer = x -> System.out.println(x); + printer.accept(LocalDate.now()); // will print the current date - BiConsumer impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); }; - impressor2.accept(LocalDate.now(), LocalTime.now()); // imprimirá a data atual e depois a hora atual + BiConsumer printer2 = (x, y) -> { System.out.println(x); System.out.println(y); }; + printer2.accept(LocalDate.now(), LocalTime.now()); // will print the current date and then the current time } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java index c7bef69..3a3b375 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java @@ -8,11 +8,11 @@ public class BuiltInInterfaces_ConsumerPrimitive { // tag::code[] public static void main(String[] args) { - IntConsumer impressor = x -> System.out.println(x); - impressor.accept(5); // imprimirá '5' + IntConsumer printer = x -> System.out.println(x); + printer.accept(5); // will print '5' - ObjIntConsumer impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); }; - impressor2.accept(LocalDate.now(), 5); // imprimirá a data atual e depois '5' + ObjIntConsumer printer2 = (x, y) -> { System.out.println(x); System.out.println(y); }; + printer2.accept(LocalDate.now(), 5); // will print the current date and then '5' } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionExample.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionExample.java index a7a9534..9574f09 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionExample.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionExample.java @@ -7,11 +7,11 @@ public class BuiltInInterfaces_FunctionExample { // tag::code[] public static void main(String[] args) { - Function duplica = x -> x * 2.5; - System.out.println(duplica.apply(3)); // multiplica 3 * 2.5 + Function duplicate = x -> x * 2.5; + System.out.println(duplicate.apply(3)); // multiply 3 * 2.5 - BiFunction multiplicaEDuplica = (x, y) -> x * y * 2.5; - System.out.println(multiplicaEDuplica.apply(3, 4)); // multiplica 3 * 4 * 2.5 + BiFunction multiplyAndDuplicate = (x, y) -> x * y * 2.5; + System.out.println(multiplyAndDuplicate.apply(3, 4)); // multiply 3 * 4 * 2.5 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java index c11fb24..0158a93 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java @@ -1,5 +1,7 @@ package org.j6toj8.lambda.builtininterfaces; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.IntToDoubleFunction; import java.util.function.ToDoubleBiFunction; @@ -7,11 +9,11 @@ public class BuiltInInterfaces_FunctionPrimitive { // tag::code[] public static void main(String[] args) { - IntToDoubleFunction duplica = x -> x * 2.5; - System.out.println(duplica.applyAsDouble(3)); // multiplica 3 * 2.5 + IntToDoubleFunction duplicate = x -> x * 2.5; + System.out.println(duplicate.applyAsDouble(3)); // multiply 3 * 2.5 - ToDoubleBiFunction multiplicaEDuplica = (x, y) -> x * y * 2.5; - System.out.println(multiplicaEDuplica.applyAsDouble(3, 4)); // multiplica 3 * 4 * 2.5 + ToDoubleBiFunction multiplyAndDuplicate = (x, y) -> x * y * 2.5; + System.out.println(multiplyAndDuplicate.applyAsDouble(3, 4)); // multiply 3 * 4 * 2.5 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorExample.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorExample.java index 59c2cb0..9b47670 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorExample.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorExample.java @@ -7,11 +7,11 @@ public class BuiltInInterfaces_OperatorExample { // tag::code[] public static void main(String[] args) { - UnaryOperator somaDois = x -> x + 2; - System.out.println(somaDois.apply(7)); // soma 7 + 2 + UnaryOperator sumTwo = x -> x + 2; + System.out.println(sumTwo.apply(7)); // sum 7 + 2 - BinaryOperator somaNumeros = (x, y) -> x + y; - System.out.println(somaNumeros.apply(1, 5)); // soma 1 + 5 + BinaryOperator sumNumbers = (x, y) -> x + y; + System.out.println(sumNumbers.apply(1, 5)); // sum 1 + 5 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java index 657bd98..28989ae 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java @@ -7,11 +7,11 @@ public class BuiltInInterfaces_OperatorPrimitive { // tag::code[] public static void main(String[] args) { - IntUnaryOperator somaDois = x -> x + 2; - System.out.println(somaDois.applyAsInt(7)); // soma 7 + 2 + IntUnaryOperator sumTwo = x -> x + 2; + System.out.println(sumTwo.applyAsInt(7)); // sum 7 + 2 - IntBinaryOperator somaNumeros = (x, y) -> x + y; - System.out.println(somaNumeros.applyAsInt(1, 5)); // soma 1 + 5 + IntBinaryOperator sumNumbers = (x, y) -> x + y; + System.out.println(sumNumbers.applyAsInt(1, 5)); // sum 1 + 5 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalCreation.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalCreation.java index cde58d0..7067aed 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalCreation.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalCreation.java @@ -5,33 +5,33 @@ public class BuiltInInterfaces_OptionalCreation { // tag::code[] - // Exemplo de método sem Optional - private static String recupereNomeMes(int mes) { - if (mes == 1) { - return "Janeiro"; + // method example without Optional + private static String retrieveMonthName(int month) { + if (month == 1) { + return "January"; } else { return null; } } - // Exemplo de método retornando Optional - private static Optional recupereNomeMesOptional(int mes) { - if (mes == 1) { - return Optional.of("Janeiro"); // cria Optional com valor + // method example returning Optional + private static Optional retrieveMonthNameOptional(int month) { + if (month == 1) { + return Optional.of("January"); // create Optional with value } else { - return Optional.empty(); // cria Optional vazio + return Optional.empty(); // create empty Optional } } public static void main(String[] args) { - String nomeMes1 = recupereNomeMes(1); - if (nomeMes1 != null) { // valida se o valor existe através da tradicional comparação '!= null' - System.out.println(nomeMes1); + String monthName1 = retrieveMonthName(1); + if (monthName1 != null) { // validates if value exists through traditional comparison '! = null' + System.out.println(monthName1); } - Optional nomeMes2 = recupereNomeMesOptional(1); - if (nomeMes2.isPresent()) { // valida se o Optional possui um valor preenchido - System.out.println(nomeMes2.get()); // recupera o valor dentro do Optional + Optional monthName2 = retrieveMonthNameOptional(1); + if (monthName2.isPresent()) { // validates if Optional has a filled value + System.out.println(monthName2.get()); // retrieve value within Optional } } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java index 1f42c36..60d27a1 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java @@ -6,11 +6,11 @@ public class BuiltInInterfaces_OptionalGetEmpty { public static void main(String[] args) { // tag::code[] - Optional optionalComValor = Optional.of("valor"); - System.out.println(optionalComValor.get()); // recupera o valor corretamente + Optional optionalWithValue = Optional.of("value"); + System.out.println(optionalWithValue.get()); // retrieve value correctly - Optional optionalVazio = Optional.empty(); - System.out.println(optionalVazio.get()); // lança exceção + Optional emptyOptional = Optional.empty(); + System.out.println(emptyOptional.get()); // throws exception // end::code[] } diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java index e79c58b..d3dc036 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java @@ -6,13 +6,13 @@ public class BuiltInInterfaces_OptionalIfPresent { // tag::code[] public static void main(String[] args) { - Optional optionalVazio = Optional.empty(); - Optional optionalComValor = Optional.of("valor"); + Optional emptyOptional = Optional.empty(); + Optional optionalWithValue = Optional.of("value"); - // A linha abaixo não irá imprimir nada, pois o optional está vazio - optionalVazio.ifPresent(valor -> System.out.println("Vazio: " + valor)); - // A linha abaixo irá imprimir, pois o optional possui valor - optionalComValor.ifPresent(valor -> System.out.println("Com Valor: " + valor )); + // The line below will not print anything as optional is empty + emptyOptional.ifPresent(value -> System.out.println("Empty: " + value)); + // The line below will print, as optional has value + optionalWithValue.ifPresent(value -> System.out.println("With Value: " + value )); } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalNullable.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalNullable.java index 17a7e83..3987fb1 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalNullable.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalNullable.java @@ -6,16 +6,16 @@ public class BuiltInInterfaces_OptionalNullable { // tag::code[] public static void main(String[] args) { - // Exemplo tentando utilizar .of e passando 'null' como argumento + // Example trying to use .of and passing 'null' as argument try { - Optional.of(null); // Lança NullPointerException nesta linha + Optional.of(null); // Throws NullPointerException on this line } catch (Exception e) { e.printStackTrace(); } - // Exemplo utilizando o método correto: .ofNullable + // Example using the correct method: .ofNullable Optional ofNullable = Optional.ofNullable(null); // Cria um Optional vazio - System.out.println(ofNullable.isPresent()); // Imprime 'false' pois não possui valor + System.out.println(ofNullable.isPresent()); // Print 'false' as it has no value } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java index 0ade442..bdd30a9 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElse.java @@ -6,22 +6,22 @@ public class BuiltInInterfaces_OptionalOrElse { // tag::code[] public static void main(String[] args) { - // Exemplo com Optional vazio - Optional optionalVazio = Optional.empty(); + // Example with empty Optional + Optional emptyOptional = Optional.empty(); - // as duas variáveis abaixo terão a String "valor padrao", pois o optional está vazio - String orElse = optionalVazio.orElse("valor padrao"); // obtém a String diretamente - String orElseGet = optionalVazio.orElseGet(() -> { return "valor padrao"; }); // obtém a String através da expressão lambda + // the two variables below will have the string "default value" because optional is empty + String orElse = emptyOptional.orElse("default value"); // get the String directly + String orElseGet = emptyOptional.orElseGet(() -> { return "default value"; }); // get String through lambda expression System.out.println(orElse); System.out.println(orElseGet); - // Exemplo com Optional com valor - Optional optionalComValor = Optional.of("valor"); + // Example with Optional with value + Optional optionalWithValue = Optional.of("value"); - // as duas variáveis abaixo irão utilizar o valor presente no optional, pois ele já está preenchido - String orElse2 = optionalComValor.orElse("valor padrao"); - String orElseGet2 = optionalComValor.orElseGet(() -> { return "valor padrao"; }); + // the two variables below will use the value present in optional as it is already filled + String orElse2 = optionalWithValue.orElse("default value"); + String orElseGet2 = optionalWithValue.orElseGet(() -> { return "default value"; }); System.out.println(orElse2); System.out.println(orElseGet2); diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java index 834196a..be24fc4 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java @@ -6,15 +6,15 @@ public class BuiltInInterfaces_OptionalOrElseThrow { // tag::code[] public static void main(String[] args) { - Optional optionalVazio = Optional.empty(); - Optional optionalComValor = Optional.of("valor"); + Optional emptyOptional = Optional.empty(); + Optional optionalWithValue = Optional.of("value"); - // Nesse caso será impresso o valor presente em Optional, pois ele está preenchido - String orElseThrow1 = optionalComValor.orElseThrow(() -> new RuntimeException()); + // In this case the value present in Optional will be printed as it is filled + String orElseThrow1 = optionalWithValue.orElseThrow(() -> new RuntimeException()); System.out.println(orElseThrow1); - // Nesse caso será lançada exceção, pois o Optional não está preenchido - String orElseThrow2 = optionalVazio.orElseThrow(() -> new RuntimeException()); + // In this case exception will be thrown because Optional is not populated + String orElseThrow2 = emptyOptional.orElseThrow(() -> new RuntimeException()); } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java index 3a4d7ef..b3772dc 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java @@ -6,14 +6,14 @@ public class BuiltInInterfaces_OptionalPrimitive { public static void main(String[] args) { // tag::code[] - OptionalInt optionalComValor = OptionalInt.of(5); - OptionalInt optionalVazio = OptionalInt.empty(); + OptionalInt optionalWithValue = OptionalInt.of(5); + OptionalInt emptyOptional = OptionalInt.empty(); - if (optionalComValor.isPresent()) { - System.out.println(optionalComValor.getAsInt()); + if (optionalWithValue.isPresent()) { + System.out.println(optionalWithValue.getAsInt()); } - if (optionalVazio.isPresent()) { - System.out.println(optionalVazio.getAsInt()); + if (emptyOptional.isPresent()) { + System.out.println(emptyOptional.getAsInt()); } // end::code[] } diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicateExample.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicateExample.java index 85a9fba..7273de0 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicateExample.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicateExample.java @@ -8,12 +8,11 @@ public class BuiltInInterfaces_PredicateExample { // tag::code[] public static void main(String[] args) { - Predicate dado = x -> x.equals(new Random().nextInt(7)); - System.out.println(dado.test(1)); // testa se o número gerado é igual a 1 + Predicate dice = x -> x.equals(new Random().nextInt(7)); + System.out.println(dice.test(1)); // tests if the generated number is equal to 1 - BiPredicate dadoDuplo = (x, y) -> x.equals(new Random().nextInt(7)) || y.equals(new Random().nextInt(7)); - System.out.println(dadoDuplo.test(1, 2)); // testa se o primeiro número gerado é igual a 1 - // ou se o segundo número gerado é igual a 2 + BiPredicate doubleDice = (x, y) -> x.equals(new Random().nextInt(7)) || y.equals(new Random().nextInt(7)); + System.out.println(doubleDice.test(1, 2)); // tests if the first generated number equals 1 or if the second generated number equals 2 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java index adb92a3..4394b18 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java @@ -7,8 +7,8 @@ public class BuiltInInterfaces_PredicatePrimitive { // tag::code[] public static void main(String[] args) { - IntPredicate dado = x -> x == new Random().nextInt(7); - System.out.println(dado.test(1)); // testa se o número gerado é igual a 1 + IntPredicate dice = x -> x == new Random().nextInt(7); + System.out.println(dice.test(1)); // tests if the generated number is equal to 1 } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierExample.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierExample.java index 1b2abab..d41f766 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierExample.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierExample.java @@ -8,7 +8,7 @@ public class BuiltInInterfaces_SupplierExample { // tag::code[] public static void main(String[] args) { Supplier supplier = () -> LocalDate.now(); - System.out.println(supplier.get()); // imprimirá a data atual + System.out.println(supplier.get()); // will print the current date } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java index ea1d51c..2b0eb5b 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java @@ -8,7 +8,7 @@ public class BuiltInInterfaces_SupplierPrimitive { // tag::code[] public static void main(String[] args) { IntSupplier randomIntSupplier = () -> new Random().nextInt(); - System.out.println(randomIntSupplier.getAsInt()); // getAsInt retorna um int primitivo + System.out.println(randomIntSupplier.getAsInt()); // getAsInt returns a primitive int } // end::code[] diff --git a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java index 2f11ee3..ff6ee49 100644 --- a/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java +++ b/src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java @@ -8,18 +8,18 @@ public class BuiltInInterfaces_SupplierUseCase { // tag::code[] - public static String valideIdade(int idade, Supplier supplier) { - if (idade < 18) { - return "Menor de idade!"; + public static String validateAge(int age, Supplier supplier) { + if (age < 18) { + return "Under age!"; } else { - return "Maior de idade! Validação realizada às " + supplier.get(); + return "Major age! Validation performed at " + supplier.get(); } } public static void main(String[] args) { Supplier supplier = () -> LocalDate.now().atTime(LocalTime.now()).format(DateTimeFormatter.ISO_DATE_TIME); - System.out.println(valideIdade(17, supplier)); - System.out.println(valideIdade(18, supplier)); + System.out.println(validateAge(17, supplier)); + System.out.println(validateAge(18, supplier)); } // end::code[] diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Basic.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Basic.java index 31dc98c..047a77b 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Basic.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Basic.java @@ -3,9 +3,9 @@ public class FunctionalInterfaces_Basic { // tag::code[] - @FunctionalInterface // a anotação não é obrigatória - interface Executavel { // interface funcional - void execute(); // método funcional + @FunctionalInterface // annotation is not required + interface Executavel { // functional interface + void execute(); // functional method } // end::code[] } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java index 14db6bf..f0d0f21 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java @@ -4,13 +4,13 @@ public class FunctionalInterfaces_ClassCompilationError { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // functional interface + void execute(); // functional method } @FunctionalInterface - class Piloto { // NÃO COMPILA! - // apenas interfaces podem ser anotadas com @FunctionalInterface + class Pilot { // NOT COMPILING! + // only interfaces can be annotated with @FunctionalInterface } // end::code[] } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java index 4fb4ce3..9bbd7a3 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java @@ -4,18 +4,18 @@ public class FunctionalInterfaces_DefaultStatic { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // functional interface + void execute(); // functional method - // métodos adicionais static são permitidos - static void execute(Executavel... executaveis) { - for (Executavel executavel : executaveis) { - executavel.execute(); + // additional static methods are allowed + static void execute(Executable... executables) { + for (Executable executable : executables) { + executable.execute(); } } - // métodos adicionais default são permitidos - default void executeDuasVezes() { + // additional default methods are allowed + default void executeTwice() { execute(); execute(); } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Extends.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Extends.java index 1f521c3..20c3fc9 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Extends.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Extends.java @@ -4,13 +4,13 @@ public class FunctionalInterfaces_Extends { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // functional interface + void execute(); // functional method } @FunctionalInterface - interface Aplicacao extends Executavel { - // também é uma interface funcional + interface Application extends Executable { + // It is also a functional interface } // end::code[] } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java index 240fb8a..b5a262e 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java @@ -4,13 +4,14 @@ public class FunctionalInterfaces_ExtendsNewMethod { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // functional interface + void execute(); // functional method + } + + @FunctionalInterface + interface Application extends Executable { + // It is NOT a functional interface as it has 2 abstract methods: execute (inherited) and init. + void init(); } - - interface Aplicacao extends Executavel { - // NÃO é uma interface funcional, pois possui 2 métodos abstratos: execute (herdado) e inicie. - void inicie(); - } // end::code[] } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Implement.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Implement.java index 7e27e7e..ead82c4 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Implement.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Implement.java @@ -4,17 +4,18 @@ public class FunctionalInterfaces_Implement { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - String execute(); // método funcional + interface Executable { // functional interface + String execute(); // functional method } - class Pessoa implements Executavel { - // COMPILA! - // interfaces funcionais, como Corredor, não foram feitas para serem implementadas dessa forma - // porém é possível e o código compila normalmente + class Person implements Executable { + + // COMPILES! + // functional interfaces, such as Executable, were not meant to be implemented this way but they are possible, and code compiles normally. + @Override public String execute() { - return "Executando"; + return "Executing"; } } // end::code[] diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java index d974ead..67f24cf 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java @@ -4,14 +4,14 @@ public class FunctionalInterfaces_InterfaceCompilationError { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // function interface + void execute(); // functional method } @FunctionalInterface - interface Aplicacao extends Executavel { // NÃO COMPILA! - // não pode ser anotada como funcional, pois possui 2 métodos abstratos - void inicie(); + interface Application extends Executable { // NOT COMPILING! + // cannot be annotated as functional as it has 2 abstract methods + void init(); } // end::code[] } diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_OverrideObject.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_OverrideObject.java index cbcc901..d9cc086 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_OverrideObject.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_OverrideObject.java @@ -4,10 +4,10 @@ public class FunctionalInterfaces_OverrideObject { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - void execute(); // método funcional + interface Executable { // functional interface + void execute(); // functional method - // sobrescrevendo métodos de Object + // overriding Object methods @Override String toString(); @Override diff --git a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ReturnType.java b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ReturnType.java index c708691..e5dbef2 100644 --- a/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ReturnType.java +++ b/src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ReturnType.java @@ -4,8 +4,8 @@ public class FunctionalInterfaces_ReturnType { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - String execute(); // método funcional com retorno + interface Executable { // functional interface + String execute(); // functional interface with return } // end::code[] } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java index 37cbb03..606610b 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java @@ -10,16 +10,16 @@ public static void main(String[] args) { Double x2 = 2.0; Double x3 = 2.0; - // COMPILA - variável externa 'x1' é final e pode ser utilizada na expressão lambda - UnaryOperator elevarAoX1 = (Double y) -> Math.pow(y, x1); + // COMPILES - external variable 'x1' is final and can be used in lambda expression + UnaryOperator raiseToX1 = (Double y) -> Math.pow(y, x1); - // COMPILA - variável externa 'x2' não é final, mas nunca é alterada, então pode ser utilizada dentro da expressão lambda - UnaryOperator elevarAoX2 = (Double y) -> Math.pow(y, x2); + // COMPILES - external variable 'x2' is not final, but never changed, so it can be used inside the lambda expression + UnaryOperator raiseToX2 = (Double y) -> Math.pow(y, x2); - // NÃO COMPILA - variável externa 'x3' é alterada dentro desse método, então não pode ser utilizada dentro da expressão lambda - UnaryOperator elevarAoX3 = (Double y) -> Math.pow(y, x3); + // NOT COMPILING - external variable 'x3' is changed within this method, so it cannot be used within the lambda expression + UnaryOperator raiseToX3 = (Double y) -> Math.pow(y, x3); - x3 = 3.0; // alteração da variável x3 não permite que ela seja utilizada em expressões lambda + x3 = 3.0; // changing variable 'x3' does not allow it to be used in lambda expressions } // end::code[] } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java index 3dc6d68..14a7dab 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java @@ -4,29 +4,29 @@ public class LambdaExpression_Ambiguity { // tag::code[] @FunctionalInterface - interface Corredor { - void corra(); + interface Runner { + void run(); } @FunctionalInterface - interface Piloto { - void corra(); + interface Pilot { + void run(); } static class Executor { - void execute(Corredor corredor) { - corredor.corra(); + void execute(Runner runner) { + runner.run(); } - String execute(Piloto piloto) { - piloto.corra(); - return "correndo"; + String execute(Pilot pilot) { + pilot.run(); + return "running"; } } public static void main(String[] args) { Executor executor = new Executor(); - // NÃO COMPILA - não é possível determinar o tipo da expressão lambda abaixo + // NOT COMPILING - cannot determine type of lambda expression below executor.execute(() -> System.out.println("execute")); } // end::code[] diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java index 99d6dfc..7b9aa7b 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java @@ -4,16 +4,16 @@ public class LambdaExpression_AnonymousClass { public static void main(String[] args) { // tag::code[] - // com classe anônima + // with anonymous class new Thread(new Runnable() { @Override public void run() { - System.out.println("Executando."); + System.out.println("Executing."); } }).run(); - // com expressão lambda - new Thread(() -> System.out.println("Executando.")).run(); + // with lambda expression + new Thread(() -> System.out.println("Executing.")).run(); // end::code[] } } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java index 8f37b98..752e392 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java @@ -7,12 +7,12 @@ public class LambdaExpression_Block { public static void main(String[] args) { // tag::code[] - UnaryOperator elevarAoQuadrado = (Double x) -> { + UnaryOperator square = (Double x) -> { double pow = Math.pow(x, 2); return pow; }; - Consumer imprime = (Double x) -> { + Consumer print = (Double x) -> { double pow = Math.pow(x, 2); System.out.println(pow); }; diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java index 36eab1c..da08b65 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java @@ -7,8 +7,8 @@ public class LambdaExpression_ForEach { public static void main(String[] args) { // tag::code[] - List lista = Arrays.asList(1, 2, 3, 4, 5); - lista.forEach((numero) -> { System.out.println(numero); }); + List list = Arrays.asList(1, 2, 3, 4, 5); + list.forEach((number) -> { System.out.println(number); }); // end::code[] } } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java index d740ff4..8bfaa09 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java @@ -4,27 +4,27 @@ public class LambdaExpression_FunctionalInterface { // tag::code[] @FunctionalInterface - interface Executavel { // interface funcional - String execute(); // método funcional + interface Executable { // functional interface + String execute(); // functional method } - private static void executeEApresenteMensagem(Executavel executavel) { - String mensagem = executavel.execute(); - System.out.println(mensagem); + private static void executeAndPresentMessage(Executable executable) { + String message = executable.execute(); + System.out.println(message); } public static void main(String[] args) { - // com classe anônima - executeEApresenteMensagem(new Executavel() { + // with anonymous class + executeAndPresentMessage(new Executable() { @Override public String execute() { - return "executei com classe anônima"; + return "performed with anonymous class"; } }); - // com expressão lambda - executeEApresenteMensagem(() -> { return "executei com expressão lambda"; }); + // with lambda expression + executeAndPresentMessage(() -> { return "performed with lambda expression"; }); } // end::code[] } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Parenthesis.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Parenthesis.java index 6fce476..5188a21 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Parenthesis.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Parenthesis.java @@ -1,25 +1,27 @@ package org.j6toj8.lambda.lambdaexpression; +import java.util.function.BinaryOperator; +import java.util.function.Supplier; import java.util.function.UnaryOperator; public class LambdaExpression_Parenthesis { public static void main(String[] args) { // tag::code[] - // NÃO COMPILA - parênteses são obrigatórios ao declarar o tipo da variável da expressão lambda - UnaryOperator elevarAoQuadrado = Double x -> Math.pow(x, 2); + // NOT COMPILING - parentheses are required when declaring the type of the lambda expression variable + UnaryOperator square = Double x -> Math.pow(x, 2); - // NÃO COMPILA - é obrigatório utilizar parênteses quando há mais de uma variável na expressão lambda - BinaryOperator elevarAoX = y, x -> Math.pow(y, x); + // NOT COMPILING - parentheses are required when there is more than one variable in the lambda expression + BinaryOperator raiseToX = y, x -> Math.pow(y, x); - // NÃO COMPILA - é obrigatório utilizar parênteses quando não há variáveis - Supplier elevar2aoQuadrado = -> Math.pow(2, 2); + // NOT COMPILING - parentheses are required when there are no variables + Supplier square2 = -> Math.pow(2, 2); - // COMPILA - parênteses vazios quando não há variáveis - Supplier elevar2aoQuadrado = () -> Math.pow(2, 2); + // COMPILES - empty parentheses when there are no variables + Supplier square3 = () -> Math.pow(2, 2); - // COMPILA - sem parênteses quando há apenas uma variável e não escrevemos seu tipo - UnaryOperator elevarAoQuadrado2 = x -> Math.pow(x, 2); + // COMPILES - no parentheses when there's only one variable and we don't write its type + UnaryOperator square4 = x -> Math.pow(x, 2); // end::code[] } } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Shadowing.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Shadowing.java index f88957e..a538b01 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Shadowing.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Shadowing.java @@ -7,13 +7,13 @@ public class LambdaExpression_Shadowing { // tag::code[] public static void main(String[] args) { - Double x = 2.0; // variável 'x' no método + Double x = 2.0; // 'x' variable in method - // NÃO COMPILA - a variável com nome 'x' já existe e não pode ser declarada nas variáveis da expressão lambda - BinaryOperator elevarAoX = (Double y, Double x) -> Math.pow(y, x); + // NOT COMPILING - variable named 'x' already exists and cannot be declared in lambda expression variables + BinaryOperator raiseToX = (Double y, Double x) -> Math.pow(y, x); - // NÃO COMPILA - a variável com nome 'x' já existe e não pode ser declarada no corpo da expressão lambda - UnaryOperator elevarAoQuadrado = (Double y) -> { + // NOT COMPILING - variable named 'x' already exists and cannot be declared in lambda expression body + UnaryOperator square = (Double y) -> { Double x = 2.0; return Math.pow(y, x); }; diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_SimpleComplete.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_SimpleComplete.java index 46c2f66..39fe588 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_SimpleComplete.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_SimpleComplete.java @@ -6,10 +6,10 @@ public class LambdaExpression_SimpleComplete { public static void main(String[] args) { // tag::code[] - // expressão lambda completa - UnaryOperator elevarAoQuadrado1 = (Double x) -> { return Math.pow(x, 2); }; - // expressão lambda simplificada - UnaryOperator elevarAoQuadrado2 = (x) -> Math.pow(x, 2); + // complete lambda expression + UnaryOperator square1 = (Double x) -> { return Math.pow(x, 2); }; + // simplified lambda expression + UnaryOperator square2 = (x) -> Math.pow(x, 2); // end::code[] } } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_TypeInference.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_TypeInference.java index ff59016..51d587c 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_TypeInference.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_TypeInference.java @@ -4,31 +4,31 @@ public class LambdaExpression_TypeInference { // tag::code[] @FunctionalInterface - interface Executavel { - void execute(); // método funcional sem argumentos + interface Executable { + void execute(); // functional method without arguments } @FunctionalInterface interface Application { - String run(); // método funcional também sem argumentos + String run(); // functional method also without arguments } static class Executor { - // esse método pode receber uma expressão lambda sem argumentos - void rode(Executavel executavel) { - executavel.execute(); + // this method can get a lambda expression with no arguments + void doThis(Executable executable) { + executable.execute(); } - // esse método também pode receber uma expressão lambda sem argumentos - void rode(Application application) { + // this method can also get a lambda expression without arguments + void doThis(Application application) { application.run(); } } public static void main(String[] args) { Executor executor = new Executor(); - executor.rode(() -> { return "executando"; }); // irá chamar o execute que recebe uma Application - executor.rode(() -> { System.out.println("executando"); }); // irá chamar o execute que recebe um Executavel + executor.doThis(() -> { return "executing"; }); // will call execute that receives an Application + executor.doThis(() -> { System.out.println("executing"); }); // will call execute that gets an Executable } // end::code[] } diff --git a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_VarType.java b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_VarType.java index 07f6dd3..5deaf0f 100644 --- a/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_VarType.java +++ b/src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_VarType.java @@ -1,16 +1,16 @@ package org.j6toj8.lambda.lambdaexpression; -import java.util.function.UnaryOperator; +import java.util.function.BinaryOperator; public class LambdaExpression_VarType { public static void main(String[] args) { // tag::code[] - // NÃO COMPILA - caso o tipo de um dos parâmetros for informado, é necessário informar de todos eles - UnaryOperator elevarAoX = (Double y, x) -> Math.pow(y, x); + // NOT COMPILING - if the type of one of the parameters is entered, all of them must be entered. + BinaryOperator raiseToX = (Double y, x) -> Math.pow(y, x); - // COMPILA - todos os parâmetros com tipos informados - UnaryOperator elevarAoX2 = (Double y, Double x) -> Math.pow(y, x); + // COMPILES - all parameters with informed types + BinaryOperator raiseToX2 = (Double y, Double x) -> Math.pow(y, x); // end::code[] } } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Complex.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Complex.java index b254136..055dff8 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Complex.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Complex.java @@ -6,8 +6,8 @@ public class MethodReference_Complex { public static void main(String[] args) { // tag::code[] - Function stringParaInteger1 = s -> new Integer(s + "2"); - System.out.println(stringParaInteger1.apply("1")); + Function stringToInteger1 = s -> new Integer(s + "2"); + System.out.println(stringToInteger1.apply("1")); // end::code[] } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Constructor.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Constructor.java index 6220c88..f7e5f1d 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Constructor.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Constructor.java @@ -6,14 +6,14 @@ public class MethodReference_Constructor { public static void main(String[] args) { // tag::code[] - // representação com expressão lambda - Function stringParaInteger1 = s -> new Integer(s); - // representação com referência ao construtor - Function stringParaInteger2 = Integer::new; + // representation with lambda expression + Function stringToInteger1 = s -> new Integer(s); + // representation with reference to the constructor + Function stringToInteger2 = Integer::new; - // os resultados serão iguais - System.out.println(stringParaInteger1.apply("1")); - System.out.println(stringParaInteger2.apply("1")); + // the results will be the same + System.out.println(stringToInteger1.apply("1")); + System.out.println(stringToInteger2.apply("1")); // end::code[] } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_CustomType.java b/src/org/j6toj8/lambda/methodreference/MethodReference_CustomType.java index 707bb51..b305b98 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_CustomType.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_CustomType.java @@ -6,44 +6,42 @@ public class MethodReference_CustomType { // tag::code[] - static class SuperHeroi { - private Pessoa pessoa; + static class SuperHero { + private Person person; - public SuperHeroi(Pessoa pessoa) { - this.pessoa = pessoa; + public SuperHero(Person person) { + this.person = person; } - public static SuperHeroi crieSuperHeroi(Pessoa pessoa) { - return new SuperHeroi(pessoa); + public static SuperHero createSuperHero(Person person) { + return new SuperHero(person); } - } - static class Pessoa { + static class Person { - public SuperHeroi vireSuperHeroi() { - return new SuperHeroi(this); + public SuperHero becomeSuperHero() { + return new SuperHero(this); } - } public static void main(String[] args) { - // expressões lambda equivalentes utilizando chamada a método estático - Function transformaEmHeroiStatic1 = p -> SuperHeroi.crieSuperHeroi(p); - Function transformaEmHeroiStatic2 = SuperHeroi::crieSuperHeroi; - - // expressões lambda equivalentes utilizando construtor - Function transformaEmHeroiConstrutor1 = p -> new SuperHeroi(p); - Function transformaEmHeroiConstrutor2 = SuperHeroi::new; - - // expressões lambda equivalentes utilizando chamada de método comum, mas referenciando o método da classe - Function transformaEmHeroiClasse1 = p -> p.vireSuperHeroi(); - Function transformaEmHeroiClasse2 = Pessoa::vireSuperHeroi; - - // expressões lambda equivalentes utilizando chamada de método comum, mas referenciando o método do objeto - Pessoa pessoa = new Pessoa(); - Supplier transformaEmHeroiInstancia1 = () -> pessoa.vireSuperHeroi(); - Supplier transformaEmHeroiInstancia2 = pessoa::vireSuperHeroi; + // equivalent lambda expressions using static method call + Function static1 = p -> SuperHero.createSuperHero(p); + Function static2 = SuperHero::createSuperHero; + + // equivalent lambda expressions using constructor + Function construtor1 = p -> new SuperHero(p); + Function construtor2 = SuperHero::new; + + // equivalent lambda expressions using common method call, but referencing class method + Function classe1 = p -> p.becomeSuperHero(); + Function classe2 = Person::becomeSuperHero; + + // equivalent lambda expressions using common method call, but referencing object method + Person person = new Person(); + Supplier instancia1 = () -> person.becomeSuperHero(); + Supplier instancia2 = person::becomeSuperHero; } // end::code[] diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Instance.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Instance.java index 823d734..bab1153 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Instance.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Instance.java @@ -5,23 +5,23 @@ public class MethodReference_Instance { // tag::code[] - static class Conversor { - public String converte(Integer x, Integer y) { + static class Converter { + public String convert(Integer x, Integer y) { return String.valueOf(x) + " - " + String.valueOf(y); } } public static void main(String[] args) { - Conversor conversor = new Conversor(); // instância da classe Conversor + Converter converter = new Converter(); // instance of the Converter class - // representação com expressão lambda - BiFunction converte1 = (x, y) -> conversor.converte(x, y); - // representação com referência ao método da instância - BiFunction converte2 = conversor::converte; + // representation with lambda expression + BiFunction convert1 = (x, y) -> converter.convert(x, y); + // representation with reference to instance method + BiFunction convert2 = converter::convert; - // os resultados serão iguais - System.out.println(converte1.apply(5, 8)); - System.out.println(converte2.apply(5, 8)); + // the results will be the same + System.out.println(convert1.apply(5, 8)); + System.out.println(convert2.apply(5, 8)); } // end::code[] diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Static.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Static.java index 8cc7bd8..6cd6a12 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Static.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Static.java @@ -6,13 +6,13 @@ public class MethodReference_Static { public static void main(String[] args) { // tag::code[] - // representação com expressão lambda - Function converteIntEmStr1 = x -> String.valueOf(x); - // representação com referência ao método - Function converteIntEmStr2 = String::valueOf; + // representation with lambda expression + Function convertIntToStr1 = x -> String.valueOf(x); + // representation with reference to the method + Function convertIntToStr2 = String::valueOf; - System.out.println(converteIntEmStr1.apply(5)); - System.out.println(converteIntEmStr2.apply(5)); + System.out.println(convertIntToStr1.apply(5)); + System.out.println(convertIntToStr2.apply(5)); // end::code[] } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Type.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Type.java index f4c925d..ee0d681 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Type.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Type.java @@ -6,14 +6,14 @@ public class MethodReference_Type { public static void main(String[] args) { // tag::code[] - // representação com expressão lambda - Function intParaDouble1 = x -> x.doubleValue(); - // representação com referência ao método doubleValue - Function intParaDouble2 = Integer::doubleValue; + // representation with lambda expression + Function intToDouble1 = x -> x.doubleValue(); + // representation with reference to the doubleValue method + Function intToDouble2 = Integer::doubleValue; - // os resultados serão iguais - System.out.println(intParaDouble1.apply(8)); - System.out.println(intParaDouble2.apply(8)); + // the results will be the same + System.out.println(intToDouble1.apply(8)); + System.out.println(intToDouble2.apply(8)); // end::code[] } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_TypeWithParam.java b/src/org/j6toj8/lambda/methodreference/MethodReference_TypeWithParam.java index befed65..9622536 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_TypeWithParam.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_TypeWithParam.java @@ -6,14 +6,14 @@ public class MethodReference_TypeWithParam { public static void main(String[] args) { // tag::code[] - // representação com expressão lambda - BiFunction comparador1 = (x, y) -> x.compareTo(y); - // representação com referência ao método compareTo do tipo Integer (que recebe um parâmetro) - BiFunction comparador2 = Integer::compareTo; + // representation with lambda expression + BiFunction comparator1 = (x, y) -> x.compareTo(y); + // representation with reference to compareTo method of type Integer (which takes a parameter) + BiFunction comparator2 = Integer::compareTo; - // os resultados serão iguais - System.out.println(comparador1.apply(1, 2)); - System.out.println(comparador2.apply(1, 2)); + // the results will be the same + System.out.println(comparator1.apply(1, 2)); + System.out.println(comparator2.apply(1, 2)); // end::code[] } diff --git a/src/org/j6toj8/lambda/methodreference/MethodReference_Variaty.java b/src/org/j6toj8/lambda/methodreference/MethodReference_Variaty.java index d46345b..a42277b 100644 --- a/src/org/j6toj8/lambda/methodreference/MethodReference_Variaty.java +++ b/src/org/j6toj8/lambda/methodreference/MethodReference_Variaty.java @@ -6,7 +6,7 @@ public class MethodReference_Variaty { public static void main(String[] args) { // tag::code[] - // ATENÇÃO! Todas essas expressões lambda são equivalentes! + // ATTENTION! All of these lambda expressions are equivalent! Function lambda1 = (Integer x) -> { return String.valueOf(x); }; Function lambda2 = (x) -> { return String.valueOf(x); }; diff --git a/src/org/j6toj8/localization/datetime/duration/Duration_Between.java b/src/org/j6toj8/localization/datetime/duration/Duration_Between.java index 4857934..f8138c0 100644 --- a/src/org/j6toj8/localization/datetime/duration/Duration_Between.java +++ b/src/org/j6toj8/localization/datetime/duration/Duration_Between.java @@ -7,14 +7,14 @@ public class Duration_Between { public static void main(String[] args) { // tag::code[] - LocalTime meiaNoite = LocalTime.of(0, 0, 0); - LocalTime meioDia = LocalTime.of (12, 0, 0); + LocalTime midnight = LocalTime.of(0, 0, 0); + LocalTime noon = LocalTime.of (12, 0, 0); - System.out.println(Duration.between(meiaNoite, meioDia)); + System.out.println(Duration.between(midnight, noon)); - System.out.println(Duration.between(meioDia, meiaNoite)); + System.out.println(Duration.between(noon, midnight)); - System.out.println(Duration.between(meioDia, meioDia)); + System.out.println(Duration.between(noon, noon)); // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/duration/Duration_BiggerValues.java b/src/org/j6toj8/localization/datetime/duration/Duration_BiggerValues.java index d51b0ae..de95d2e 100644 --- a/src/org/j6toj8/localization/datetime/duration/Duration_BiggerValues.java +++ b/src/org/j6toj8/localization/datetime/duration/Duration_BiggerValues.java @@ -6,10 +6,10 @@ public class Duration_BiggerValues { public static void main(String[] args) { // tag::code[] - System.out.println(Duration.ofMinutes(120)); // 120 minutos - System.out.println(Duration.ofMinutes(121)); // 2 horas e 1 minuto - System.out.println(Duration.ofMinutes(119)); // 1 hora e 59 minutos - System.out.println(Duration.ofSeconds(10000)); // 2 horas, 46 minutos e 40 segundos + System.out.println(Duration.ofMinutes(120)); // 120 minutes + System.out.println(Duration.ofMinutes(121)); // 2 hours and 1 minute + System.out.println(Duration.ofMinutes(119)); // 1 hour and 59 minutes + System.out.println(Duration.ofSeconds(10000)); // 2 hours, 46 minutes and 40 seconds // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/duration/Duration_Compatibility.java b/src/org/j6toj8/localization/datetime/duration/Duration_Compatibility.java index a6bbfc6..dadc91f 100644 --- a/src/org/j6toj8/localization/datetime/duration/Duration_Compatibility.java +++ b/src/org/j6toj8/localization/datetime/duration/Duration_Compatibility.java @@ -21,7 +21,7 @@ public static void main(String[] args) { System.out.println("LocalTime + Duration: " + localTime.plus(period)); LocalDateTime localDateTime = LocalDateTime.of(2018, 05, 27, 13, 1, 1); - System.out.println("\nLocalDateTime: " +localDateTime); + System.out.println("\nLocalDateTime: " + localDateTime); System.out.println("LocalDateTime + Duration: " + localDateTime.plus(period)); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/duration/Duration_Of.java b/src/org/j6toj8/localization/datetime/duration/Duration_Of.java index 196a113..30e8512 100644 --- a/src/org/j6toj8/localization/datetime/duration/Duration_Of.java +++ b/src/org/j6toj8/localization/datetime/duration/Duration_Of.java @@ -7,14 +7,14 @@ public class Duration_Of { public static void main(String[] args) { // tag::code[] - System.out.println(Duration.ofNanos(2)); // 2 nanossegundos - System.out.println(Duration.ofMillis(2)); // 2 milissegundos - System.out.println(Duration.ofSeconds(2)); // 2 segundos - System.out.println(Duration.ofMinutes(2)); // 2 minutos - System.out.println(Duration.ofHours(2)); // 2 horas - System.out.println(Duration.ofDays(2)); // 2 dias (48 horas) - System.out.println(Duration.ofSeconds(2, 200)); // 2,0000002 segundos (2 segundos e 200 nanossegundos) - System.out.println(Duration.of(2, ChronoUnit.MICROS)); // 2 microssegundos + System.out.println(Duration.ofNanos(2)); // 2 nanoseconds + System.out.println(Duration.ofMillis(2)); // 2 milliseconds + System.out.println(Duration.ofSeconds(2)); // 2 seconds + System.out.println(Duration.ofMinutes(2)); // 2 minutes + System.out.println(Duration.ofHours(2)); // 2 hours + System.out.println(Duration.ofDays(2)); // 2 days (48 hours) + System.out.println(Duration.ofSeconds(2, 200)); // 2,0000002 seconds (2 seconds e 200 nanoseconds) + System.out.println(Duration.of(2, ChronoUnit.MICROS)); // 2 microseconds // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/instant/Instant_Constructor.java b/src/org/j6toj8/localization/datetime/instant/Instant_Constructor.java index e02ea36..99b1812 100644 --- a/src/org/j6toj8/localization/datetime/instant/Instant_Constructor.java +++ b/src/org/j6toj8/localization/datetime/instant/Instant_Constructor.java @@ -6,7 +6,7 @@ public class Instant_Constructor { public static void main(String[] args) { // tag::code[] - Instant instant = new Instant(); // NÃO COMPILA! - não possui construtor padrão + Instant instant = new Instant(); // NOT COMPILING! - has no default constructor System.out.println(instant); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/instant/Instant_Convert.java b/src/org/j6toj8/localization/datetime/instant/Instant_Convert.java index 014b239..18e97c5 100644 --- a/src/org/j6toj8/localization/datetime/instant/Instant_Convert.java +++ b/src/org/j6toj8/localization/datetime/instant/Instant_Convert.java @@ -13,7 +13,7 @@ public static void main(String[] args) { System.out.println(localDateTime.toInstant(ZoneOffset.UTC)); System.out.println(localDateTime.toInstant(ZoneOffset.of("-3"))); - Instant instant = Instant.ofEpochSecond(1558962061L); // mesma data do localDateTime + Instant instant = Instant.ofEpochSecond(1558962061L); // same date as localDateTime System.out.println("\nInstant: " + instant); System.out.println(LocalDateTime.ofInstant(instant, ZoneOffset.UTC)); System.out.println(LocalDateTime.ofInstant(instant, ZoneOffset.of("-3"))); diff --git a/src/org/j6toj8/localization/datetime/instant/Instant_Immutability.java b/src/org/j6toj8/localization/datetime/instant/Instant_Immutability.java index 81b85eb..f8b728a 100644 --- a/src/org/j6toj8/localization/datetime/instant/Instant_Immutability.java +++ b/src/org/j6toj8/localization/datetime/instant/Instant_Immutability.java @@ -8,9 +8,9 @@ public static void main(String[] args) { // tag::code[] Instant instant = Instant.ofEpochMilli(1000000000000L); System.out.println(instant); - instant.plusSeconds(60); // chamada perdida - a nova data/hora não foi armazenada em uma variável + instant.plusSeconds(60); // missed call - new date/time was not stored in a variable System.out.println(instant); - instant = instant.plusSeconds(60); // chamada útil - data/hora armazenada na variável + instant = instant.plusSeconds(60); // useful call - date/time stored in variable System.out.println(instant); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/instant/Instant_Manipulate.java b/src/org/j6toj8/localization/datetime/instant/Instant_Manipulate.java index 38bfcd6..6874412 100644 --- a/src/org/j6toj8/localization/datetime/instant/Instant_Manipulate.java +++ b/src/org/j6toj8/localization/datetime/instant/Instant_Manipulate.java @@ -9,16 +9,16 @@ public static void main(String[] args) { // tag::code[] Instant instant = Instant.ofEpochMilli(1000000000000L); System.out.println(instant); - System.out.println("+2 segundos: " + instant.plusSeconds(2)); - System.out.println("+2 nanosegundos: " + instant.plusNanos(2)); - System.out.println("+2 microssegundos: " + instant.plus(2, ChronoUnit.MICROS)); - System.out.println("+2 milissegundos: " + instant.plus(2, ChronoUnit.MILLIS)); - System.out.println("-2 segundos: " + instant.minusSeconds(2)); - System.out.println("-2 nanosegundos: " + instant.minusNanos(2)); - System.out.println("-2 microssegundos: " + instant.minus(2, ChronoUnit.MICROS)); - System.out.println("-2 milissegundos: " + instant.minus(2, ChronoUnit.MILLIS)); - System.out.println("+2 dias: " + instant.plus(2, ChronoUnit.DAYS)); - System.out.println("+2 semanas: " + instant.plus(2, ChronoUnit.WEEKS)); // erro de execução + System.out.println("+2 seconds: " + instant.plusSeconds(2)); + System.out.println("+2 nanoseconds: " + instant.plusNanos(2)); + System.out.println("+2 microseconds: " + instant.plus(2, ChronoUnit.MICROS)); + System.out.println("+2 milliseconds: " + instant.plus(2, ChronoUnit.MILLIS)); + System.out.println("-2 seconds: " + instant.minusSeconds(2)); + System.out.println("-2 nanoseconds: " + instant.minusNanos(2)); + System.out.println("-2 microseconds: " + instant.minus(2, ChronoUnit.MICROS)); + System.out.println("-2 milliseconds: " + instant.minus(2, ChronoUnit.MILLIS)); + System.out.println("+2 days: " + instant.plus(2, ChronoUnit.DAYS)); + System.out.println("+2 weeks: " + instant.plus(2, ChronoUnit.WEEKS)); // runtime error // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/instant/Instant_Of.java b/src/org/j6toj8/localization/datetime/instant/Instant_Of.java index 9482369..a616bb7 100644 --- a/src/org/j6toj8/localization/datetime/instant/Instant_Of.java +++ b/src/org/j6toj8/localization/datetime/instant/Instant_Of.java @@ -8,7 +8,7 @@ public static void main(String[] args) { // tag::code[] System.out.println(Instant.ofEpochMilli(1000000000000L)); System.out.println(Instant.ofEpochSecond(1000000000)); - System.out.println(Instant.ofEpochSecond(1000000000, 123000000)); // com nanossegundos + System.out.println(Instant.ofEpochSecond(1000000000, 123000000)); // with nanoseconds // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localdate/LocalDate_AdjustDifferentUnit.java b/src/org/j6toj8/localization/datetime/localdate/LocalDate_AdjustDifferentUnit.java index 991a6c0..cfb4039 100644 --- a/src/org/j6toj8/localization/datetime/localdate/LocalDate_AdjustDifferentUnit.java +++ b/src/org/j6toj8/localization/datetime/localdate/LocalDate_AdjustDifferentUnit.java @@ -9,9 +9,9 @@ public static void main(String[] args) { // tag::code[] LocalDate localDate = LocalDate.of(2019, Month.NOVEMBER, 30); System.out.println(localDate); - System.out.println(localDate.plusDays(1)); // + 1 dia, vira o mês - System.out.println(localDate.plusDays(32)); // + 32 dias, vira o ano - System.out.println(localDate.plusMonths(2)); // + 2 meses, vira o ano + System.out.println(localDate.plusDays(1)); // + 1 day, turns the month + System.out.println(localDate.plusDays(32)); // + 32 days, turns the year + System.out.println(localDate.plusMonths(2)); // + 2 months, turns the year // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Constructor.java b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Constructor.java index 8092cd7..1a4f73f 100644 --- a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Constructor.java +++ b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Constructor.java @@ -6,7 +6,7 @@ public class LocalDate_Constructor { public static void main(String[] args) { // tag::code[] - LocalDate localDate = new LocalDate(); // NÃO COMPILA! - não possui construtor padrão + LocalDate localDate = new LocalDate(); // NOT COMPILING! - has no default constructor System.out.println(localDate); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Immutability.java b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Immutability.java index ac15e5b..3181d47 100644 --- a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Immutability.java +++ b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Immutability.java @@ -9,9 +9,9 @@ public static void main(String[] args) { // tag::code[] LocalDate localDate = LocalDate.of(2019, Month.MAY, 20); System.out.println(localDate); - localDate.plusDays(1); // chamada perdida - a nova data não foi armazenada em uma variável + localDate.plusDays(1); // missed call - new date was not stored in a variable System.out.println(localDate); - localDate = localDate.plusDays(1); // chamada útil - data armazenada na variável + localDate = localDate.plusDays(1); // useful call - date stored in variable System.out.println(localDate); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Manipulate.java b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Manipulate.java index 804a37c..5545cf0 100644 --- a/src/org/j6toj8/localization/datetime/localdate/LocalDate_Manipulate.java +++ b/src/org/j6toj8/localization/datetime/localdate/LocalDate_Manipulate.java @@ -10,17 +10,16 @@ public static void main(String[] args) { // tag::code[] LocalDate localDate = LocalDate.of(2019, Month.MAY, 20); System.out.println(localDate); - System.out.println("+2 dias: " + localDate.plusDays(2)); - System.out.println("+2 semanas: " + localDate.plusWeeks(2)); - System.out.println("+2 meses: " + localDate.plusMonths(2)); - System.out.println("+2 anos: " + localDate.plusYears(2)); - System.out.println("+2 anos: " + localDate.plusYears(2)); - System.out.println("+2 décadas: " + localDate.plus(2, ChronoUnit.DECADES)); - System.out.println("-2 dias: " + localDate.minusDays(2)); - System.out.println("-2 semanas: " + localDate.minusWeeks(2)); - System.out.println("-2 meses: " + localDate.minusMonths(2)); - System.out.println("-2 anos: " + localDate.minusYears(2)); - System.out.println("-2 décadas: " + localDate.minus(2, ChronoUnit.DECADES)); + System.out.println("+2 days: " + localDate.plusDays(2)); + System.out.println("+2 weeks: " + localDate.plusWeeks(2)); + System.out.println("+2 months: " + localDate.plusMonths(2)); + System.out.println("+2 years: " + localDate.plusYears(2)); + System.out.println("+2 decades: " + localDate.plus(2, ChronoUnit.DECADES)); + System.out.println("-2 days: " + localDate.minusDays(2)); + System.out.println("-2 weeks: " + localDate.minusWeeks(2)); + System.out.println("-2 months: " + localDate.minusMonths(2)); + System.out.println("-2 years: " + localDate.minusYears(2)); + System.out.println("-2 decades: " + localDate.minus(2, ChronoUnit.DECADES)); // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java index 54a9b0b..ae2d7c3 100644 --- a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java +++ b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java @@ -8,7 +8,7 @@ public static void main(String[] args) { // tag::code[] LocalDateTime localDateTime = LocalDateTime.of(2019, 12, 31, 23, 59, 59); System.out.println(localDateTime); - System.out.println(localDateTime.plusSeconds(2)); // + 2 segundos, vira o ano + System.out.println(localDateTime.plusSeconds(2)); // + 2 seconds, turns the year // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Constructor.java b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Constructor.java index ce094d9..84a7a39 100644 --- a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Constructor.java +++ b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Constructor.java @@ -1,12 +1,13 @@ package org.j6toj8.localization.datetime.localdatetime; import java.time.LocalDate; +import java.time.LocalDateTime; public class LocalDateTime_Constructor { public static void main(String[] args) { // tag::code[] - LocalDateTime localDateTime = new LocalDateTime(); // NÃO COMPILA! - não possui construtor padrão + LocalDateTime localDateTime = new LocalDateTime(); // NOT COMPILING! - has no default constructor System.out.println(localDateTime); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Immutability.java b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Immutability.java index 77c542e..e6680af 100644 --- a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Immutability.java +++ b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Immutability.java @@ -8,9 +8,9 @@ public static void main(String[] args) { // tag::code[] LocalDateTime localDateTime = LocalDateTime.of(2019, 5, 20, 9, 20); System.out.println(localDateTime); - localDateTime.plusHours(1); // chamada perdida - a nova data/hora não foi armazenada em uma variável + localDateTime.plusHours(1); // missed call - new date/time was not stored in a variable System.out.println(localDateTime); - localDateTime = localDateTime.plusHours(1); // chamada útil - data/hora armazenada na variável + localDateTime = localDateTime.plusHours(1); // useful call - date/time stored in variable System.out.println(localDateTime); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Invalid.java b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Invalid.java index 2561b0c..4fcc7e8 100644 --- a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Invalid.java +++ b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Invalid.java @@ -6,7 +6,7 @@ public class LocalDateTime_Invalid { public static void main(String[] args) { // tag::code[] - System.out.println(LocalDateTime.of(2019, 4, 31, 9, 20)); // lança exceção: não existe 31 de abril + System.out.println(LocalDateTime.of(2019, 4, 31, 9, 20)); // throws exception: There is no April 31 // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Manipulate.java b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Manipulate.java index 170c13e..1292402 100644 --- a/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Manipulate.java +++ b/src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Manipulate.java @@ -9,29 +9,28 @@ public static void main(String[] args) { // tag::code[] LocalDateTime localDateTime = LocalDateTime.of(2019, 5, 20, 9, 20, 12); System.out.println(localDateTime); - System.out.println("+2 horas: " + localDateTime.plusHours(2)); - System.out.println("+2 minutos: " + localDateTime.plusMinutes(2)); - System.out.println("+2 segundos: " + localDateTime.plusSeconds(2)); - System.out.println("+2 nanosegundos: " + localDateTime.plusNanos(2)); - System.out.println("+2 microssegundos: " + localDateTime.plus(2, ChronoUnit.MICROS)); - System.out.println("+2 milissegundos: " + localDateTime.plus(2, ChronoUnit.MILLIS)); - System.out.println("-2 horas: " + localDateTime.minusHours(2)); - System.out.println("-2 minutos: " + localDateTime.minusMinutes(2)); - System.out.println("-2 segundos: " + localDateTime.minusSeconds(2)); - System.out.println("-2 nanosegundos: " + localDateTime.minusNanos(2)); - System.out.println("-2 microssegundos: " + localDateTime.minus(2, ChronoUnit.MICROS)); - System.out.println("-2 milissegundos: " + localDateTime.minus(2, ChronoUnit.MILLIS)); - System.out.println("+2 dias: " + localDateTime.plusDays(2)); - System.out.println("+2 semanas: " + localDateTime.plusWeeks(2)); - System.out.println("+2 meses: " + localDateTime.plusMonths(2)); - System.out.println("+2 anos: " + localDateTime.plusYears(2)); - System.out.println("+2 anos: " + localDateTime.plusYears(2)); - System.out.println("+2 décadas: " + localDateTime.plus(2, ChronoUnit.DECADES)); - System.out.println("-2 dias: " + localDateTime.minusDays(2)); - System.out.println("-2 semanas: " + localDateTime.minusWeeks(2)); - System.out.println("-2 meses: " + localDateTime.minusMonths(2)); - System.out.println("-2 anos: " + localDateTime.minusYears(2)); - System.out.println("-2 décadas: " + localDateTime.minus(2, ChronoUnit.DECADES)); + System.out.println("+2 hours: " + localDateTime.plusHours(2)); + System.out.println("+2 minutes: " + localDateTime.plusMinutes(2)); + System.out.println("+2 seconds: " + localDateTime.plusSeconds(2)); + System.out.println("+2 nanoseconds: " + localDateTime.plusNanos(2)); + System.out.println("+2 microseconds: " + localDateTime.plus(2, ChronoUnit.MICROS)); + System.out.println("+2 milliseconds: " + localDateTime.plus(2, ChronoUnit.MILLIS)); + System.out.println("-2 hours: " + localDateTime.minusHours(2)); + System.out.println("-2 minutes: " + localDateTime.minusMinutes(2)); + System.out.println("-2 seconds: " + localDateTime.minusSeconds(2)); + System.out.println("-2 nanoseconds: " + localDateTime.minusNanos(2)); + System.out.println("-2 microseconds: " + localDateTime.minus(2, ChronoUnit.MICROS)); + System.out.println("-2 milliseconds: " + localDateTime.minus(2, ChronoUnit.MILLIS)); + System.out.println("+2 days: " + localDateTime.plusDays(2)); + System.out.println("+2 weeks: " + localDateTime.plusWeeks(2)); + System.out.println("+2 months: " + localDateTime.plusMonths(2)); + System.out.println("+2 years: " + localDateTime.plusYears(2)); + System.out.println("+2 decades: " + localDateTime.plus(2, ChronoUnit.DECADES)); + System.out.println("-2 days: " + localDateTime.minusDays(2)); + System.out.println("-2 weeks: " + localDateTime.minusWeeks(2)); + System.out.println("-2 months: " + localDateTime.minusMonths(2)); + System.out.println("-2 years: " + localDateTime.minusYears(2)); + System.out.println("-2 decades: " + localDateTime.minus(2, ChronoUnit.DECADES)); // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localtime/LocalTime_AdjustDifferentUnit.java b/src/org/j6toj8/localization/datetime/localtime/LocalTime_AdjustDifferentUnit.java index 2495887..c00ac4c 100644 --- a/src/org/j6toj8/localization/datetime/localtime/LocalTime_AdjustDifferentUnit.java +++ b/src/org/j6toj8/localization/datetime/localtime/LocalTime_AdjustDifferentUnit.java @@ -8,10 +8,10 @@ public static void main(String[] args) { // tag::code[] LocalTime localTime = LocalTime.of(9, 59, 59); System.out.println(localTime); - System.out.println(localTime.plusSeconds(2)); // + 2 segundos, vira o minuto - System.out.println(localTime.plusSeconds(62)); // + 62 segundos, vira a hora - System.out.println(localTime.plusMinutes(2)); // + 2 minutos, vira a hora - System.out.println(localTime.minusNanos(1000000000)); // - 1 segundo (em nanos), vira o minuto + System.out.println(localTime.plusSeconds(2)); // + 2 seconds, turns the minute + System.out.println(localTime.plusSeconds(62)); // + 62 seconds, turns the hour + System.out.println(localTime.plusMinutes(2)); // + 2 minutes, turns the hour + System.out.println(localTime.minusNanos(1000000000)); // - 1 second (in nanos), turns the minute // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Constructor.java b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Constructor.java index 9bfd6d5..c35e917 100644 --- a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Constructor.java +++ b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Constructor.java @@ -1,12 +1,13 @@ package org.j6toj8.localization.datetime.localtime; import java.time.LocalDate; +import java.time.LocalTime; public class LocalTime_Constructor { public static void main(String[] args) { // tag::code[] - LocalTime localTime = new LocalTime(); // NÃO COMPILA! - não possui construtor padrão + LocalTime localTime = new LocalTime(); // NOT COMPILING! - has no default constructor System.out.println(localTime); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Immutability.java b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Immutability.java index 9032203..445dd13 100644 --- a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Immutability.java +++ b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Immutability.java @@ -8,9 +8,9 @@ public static void main(String[] args) { // tag::code[] LocalTime localTime = LocalTime.of(9, 31, 5); System.out.println(localTime); - localTime.plusHours(1); // chamada perdida - a nova hora não foi armazenada em uma variável + localTime.plusHours(1); // missed call - the new time was not stored in a variable System.out.println(localTime); - localTime = localTime.plusHours(1); // chamada útil - hora armazenada na variável + localTime = localTime.plusHours(1); // useful call - time stored in variable System.out.println(localTime); // end::code[] } diff --git a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Invalid.java b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Invalid.java index dbe9ea6..66aeaf7 100644 --- a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Invalid.java +++ b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Invalid.java @@ -6,7 +6,7 @@ public class LocalTime_Invalid { public static void main(String[] args) { // tag::code[] - System.out.println(LocalTime.of(24, 2, 3)); // lança exceção: a hora deve estar entre 0 e 23 + System.out.println(LocalTime.of(24, 2, 3)); // throw exception: time must be between 0 and 23 // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Manipulate.java b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Manipulate.java index 2ba543a..4ffba53 100644 --- a/src/org/j6toj8/localization/datetime/localtime/LocalTime_Manipulate.java +++ b/src/org/j6toj8/localization/datetime/localtime/LocalTime_Manipulate.java @@ -9,18 +9,18 @@ public static void main(String[] args) { // tag::code[] LocalTime localTime = LocalTime.of(9, 26, 12); System.out.println(localTime); - System.out.println("+2 horas: " + localTime.plusHours(2)); - System.out.println("+2 minutos: " + localTime.plusMinutes(2)); - System.out.println("+2 segundos: " + localTime.plusSeconds(2)); - System.out.println("+2 nanosegundos: " + localTime.plusNanos(2)); - System.out.println("+2 microssegundos: " + localTime.plus(2, ChronoUnit.MICROS)); - System.out.println("+2 milissegundos: " + localTime.plus(2, ChronoUnit.MILLIS)); - System.out.println("-2 horas: " + localTime.minusHours(2)); - System.out.println("-2 minutos: " + localTime.minusMinutes(2)); - System.out.println("-2 segundos: " + localTime.minusSeconds(2)); - System.out.println("-2 nanosegundos: " + localTime.minusNanos(2)); - System.out.println("-2 microssegundos: " + localTime.minus(2, ChronoUnit.MICROS)); - System.out.println("-2 milissegundos: " + localTime.minus(2, ChronoUnit.MILLIS)); + System.out.println("+2 hours: " + localTime.plusHours(2)); + System.out.println("+2 minutes: " + localTime.plusMinutes(2)); + System.out.println("+2 seconds: " + localTime.plusSeconds(2)); + System.out.println("+2 nanoseconds: " + localTime.plusNanos(2)); + System.out.println("+2 microseconds: " + localTime.plus(2, ChronoUnit.MICROS)); + System.out.println("+2 milliseconds: " + localTime.plus(2, ChronoUnit.MILLIS)); + System.out.println("-2 hours: " + localTime.minusHours(2)); + System.out.println("-2 minutes: " + localTime.minusMinutes(2)); + System.out.println("-2 seconds: " + localTime.minusSeconds(2)); + System.out.println("-2 nanoseconds: " + localTime.minusNanos(2)); + System.out.println("-2 microseconds: " + localTime.minus(2, ChronoUnit.MICROS)); + System.out.println("-2 milliseconds " + localTime.minus(2, ChronoUnit.MILLIS)); // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/period/Period_Between.java b/src/org/j6toj8/localization/datetime/period/Period_Between.java index 159397d..977ec8e 100644 --- a/src/org/j6toj8/localization/datetime/period/Period_Between.java +++ b/src/org/j6toj8/localization/datetime/period/Period_Between.java @@ -7,10 +7,10 @@ public class Period_Between { public static void main(String[] args) { // tag::code[] - LocalDate nascimento = LocalDate.of(1990, 8, 6); - LocalDate hoje = LocalDate.now(); - Period idade = Period.between(nascimento, hoje); - System.out.println(idade); + LocalDate birth = LocalDate.of(1990, 8, 6); + LocalDate today = LocalDate.now(); + Period age = Period.between(birth, today); + System.out.println(age); // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/period/Period_BiggerValues.java b/src/org/j6toj8/localization/datetime/period/Period_BiggerValues.java index a183e4b..6926cf8 100644 --- a/src/org/j6toj8/localization/datetime/period/Period_BiggerValues.java +++ b/src/org/j6toj8/localization/datetime/period/Period_BiggerValues.java @@ -6,9 +6,9 @@ public class Period_BiggerValues { public static void main(String[] args) { // tag::code[] - System.out.println(Period.of(0, 60, 2)); // 60 meses e 2 dias - System.out.println(Period.of(0, 30, 50)); // 30 meses e 50 dias - System.out.println(Period.of(5, 200, 1000)); // 5 anos, 200 meses e 1000 dias + System.out.println(Period.of(0, 60, 2)); // 60 months and 2 days + System.out.println(Period.of(0, 30, 50)); // 30 months and 50 days + System.out.println(Period.of(5, 200, 1000)); // 5 years, 200 months and 1000 days // end::code[] } } diff --git a/src/org/j6toj8/localization/datetime/period/Period_Of.java b/src/org/j6toj8/localization/datetime/period/Period_Of.java index ba2f6f1..ed39a42 100644 --- a/src/org/j6toj8/localization/datetime/period/Period_Of.java +++ b/src/org/j6toj8/localization/datetime/period/Period_Of.java @@ -6,11 +6,11 @@ public class Period_Of { public static void main(String[] args) { // tag::code[] - System.out.println(Period.ofDays(2)); // período de 2 dias - System.out.println(Period.ofMonths(2)); // período de 2 meses - System.out.println(Period.ofWeeks(2)); // período de 2 semanas - System.out.println(Period.ofYears(2)); // período de 2 anos - System.out.println(Period.of(2, 1, 3)); // 2 anos, 1 mês e 3 dias + System.out.println(Period.ofDays(2)); // period of 2 days + System.out.println(Period.ofMonths(2)); // period of 2 months + System.out.println(Period.ofWeeks(2)); // period of 2 weeks + System.out.println(Period.ofYears(2)); // period of 2 years + System.out.println(Period.of(2, 1, 3)); // 2 years, 1 month and 3 days // end::code[] } } diff --git a/src/org/j6toj8/localization/formats/dateformat/DateFormat_Instance.java b/src/org/j6toj8/localization/formats/dateformat/DateFormat_Instance.java index 1853bc9..ab657ac 100644 --- a/src/org/j6toj8/localization/formats/dateformat/DateFormat_Instance.java +++ b/src/org/j6toj8/localization/formats/dateformat/DateFormat_Instance.java @@ -14,7 +14,7 @@ public static void main(String[] args) { DateFormat dateTimeLongInstance = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); DateFormat dateTimeUSInstance = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US); - Date date = new Date(1000000000000L); // data em quantidade de milissegundos desde 01/01/1970 + Date date = new Date(1000000000000L); // date in milliseconds since 01/01/1970 System.out.println(dateInstance.format(date)); System.out.println(timeInstance.format(date)); diff --git a/src/org/j6toj8/localization/formats/dateformat/DateFormat_Parse.java b/src/org/j6toj8/localization/formats/dateformat/DateFormat_Parse.java index ebf4891..7bb1f46 100644 --- a/src/org/j6toj8/localization/formats/dateformat/DateFormat_Parse.java +++ b/src/org/j6toj8/localization/formats/dateformat/DateFormat_Parse.java @@ -19,7 +19,7 @@ public static void main(String[] args) { System.out.println(dateInstance.parse(date)); System.out.println(timeInstance.parse(time)); System.out.println(dateTimeInstance.parse(dateTime)); - System.out.println(dateTimeInstance.parse(date)); // exceção, pois date não tem hora + System.out.println(dateTimeInstance.parse(date)); // exception because date has no time } catch (ParseException e) { System.out.println(e.getMessage()); } diff --git a/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Error.java b/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Error.java index 2536165..d1cd8dc 100644 --- a/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Error.java +++ b/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Error.java @@ -16,7 +16,7 @@ public static void main(String[] args) { System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE)); System.out.println(localDT.format(DateTimeFormatter.ISO_LOCAL_DATE)); - // lança exceção pois não possui campos de data + // throws exception because it has no date fields System.out.println(localTime.format(DateTimeFormatter.ISO_LOCAL_DATE)); // end::code[] } diff --git a/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java b/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java index 574e99b..ba2b1de 100644 --- a/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java +++ b/src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java @@ -17,7 +17,7 @@ public static void main(String[] args) { System.out.println(localDT.format(formatter)); System.out.println(localTime.format(formatter)); - System.out.println(localDate.format(formatter)); // lança exceção pois não possui campos de hora + System.out.println(localDate.format(formatter)); // throws exception because it has no time fields // end::code[] } } diff --git a/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Instance.java b/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Instance.java index 4289739..b61ecb8 100644 --- a/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Instance.java +++ b/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Instance.java @@ -8,31 +8,31 @@ public static void main(String[] args) { // tag::code[] double d = 12345.67; - // omite todas as posições vazias, utiliza separador a cada 3 casas + // omit all empty positions, use separator every 3 places DecimalFormat instance1 = new DecimalFormat("###,###.###"); System.out.println("###,###.###: " + instance1.format(d)); - // omite as posições vazias na parte decimal, utiliza separador a cada 3 casas + // omits empty positions in decimal, uses separator every 3 places DecimalFormat instance2 = new DecimalFormat("000,000.###"); System.out.println("000,000.###: " + instance2.format(d)); - // omite as posições vazias na parte inteira, utiliza separador a cada 3 casas + // omits empty positions on integer, uses separator every 3 places DecimalFormat instance3 = new DecimalFormat("###,###.000"); System.out.println("###,###.000: " + instance3.format(d)); - // apresenta todas as posições, utiliza separador a cada 3 casas + // displays all positions, uses separator every 3 boxes DecimalFormat instance4 = new DecimalFormat("000,000.000"); System.out.println("000,000.000: " + instance4.format(d)); - // omite todas as posições vazias, não utiliza separador + // omits all empty positions, does not use separator DecimalFormat instance5 = new DecimalFormat("###.##"); System.out.println("###.##: " + instance5.format(d)); - // apresenta todas as posições, não utiliza separador + // displays all positions, does not use separator DecimalFormat instance6 = new DecimalFormat("000000.000"); System.out.println("000000.000: " + instance6.format(d)); - // omite todas as posições vazias, não utiliza separador e não apresenta casas decimais + // omits all empty positions, does not separator and decimal places DecimalFormat instance7 = new DecimalFormat("###"); System.out.println("###: " + instance7.format(d)); // end::code[] diff --git a/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Strings.java b/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Strings.java index b0d124a..360d7fb 100644 --- a/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Strings.java +++ b/src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Strings.java @@ -8,7 +8,7 @@ public static void main(String[] args) { // tag::code[] double d = 12345.67; - DecimalFormat decimalFormat = new DecimalFormat("Número ###,###.### formatado"); + DecimalFormat decimalFormat = new DecimalFormat("Number ###,###.### formatted"); System.out.println(decimalFormat.format(d)); // end::code[] } diff --git a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Currency.java b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Currency.java index 4666ea5..552d21f 100644 --- a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Currency.java +++ b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Currency.java @@ -12,14 +12,14 @@ public static void main(String[] args) { NumberFormat currencyFormatEnUS = NumberFormat.getCurrencyInstance(new Locale("en", "US")); NumberFormat currencyFormatFrFR = NumberFormat.getCurrencyInstance(new Locale("fr", "FR")); - // Valor monetário para String + // Monetary value to String double d = 1000.05; System.out.println("pt_BR: " + currencyFormatPtBR.format(d)); System.out.println("en_US: " + currencyFormatEnUS.format(d)); System.out.println("fr_FR: " + currencyFormatFrFR.format(d)); - // String para valor Monetário + // String to monetary value String s = "R$ 1000,05"; try { diff --git a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Instance.java b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Instance.java index 90e113b..48b3565 100644 --- a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Instance.java +++ b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Instance.java @@ -7,13 +7,13 @@ public class NumberFormat_Instance { public static void main(String[] args) { // tag::code[] - // sem Locale + // without Locale NumberFormat instance1 = NumberFormat.getInstance(); - NumberFormat instance2 = NumberFormat.getNumberInstance(); // igual a getInstance() + NumberFormat instance2 = NumberFormat.getNumberInstance(); // equals to getInstance() NumberFormat instance3 = NumberFormat.getCurrencyInstance(); NumberFormat instance4 = NumberFormat.getPercentInstance(); - // com Locale + // with Locale NumberFormat instance5 = NumberFormat.getInstance(new Locale("pt", "BR")); NumberFormat instance6 = NumberFormat.getNumberInstance(new Locale("pt", "BR")); NumberFormat instance7 = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); diff --git a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent.java b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent.java index ee6c694..2f5e337 100644 --- a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent.java +++ b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent.java @@ -12,14 +12,14 @@ public static void main(String[] args) { NumberFormat percentFormatEnUS = NumberFormat.getPercentInstance(new Locale("en", "US")); NumberFormat percentFormatFrFR = NumberFormat.getPercentInstance(new Locale("fr", "FR")); - // Percentual para String + // Percent to String double d = 0.9; System.out.println("pt_BR: " + percentFormatPtBR.format(d)); System.out.println("en_US: " + percentFormatEnUS.format(d)); System.out.println("fr_FR: " + percentFormatFrFR.format(d)); - // String para Percentual + // String para Percent String s = "80%"; try { diff --git a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent2.java b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent2.java index 8aa0a08..33a74a0 100644 --- a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent2.java +++ b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent2.java @@ -11,14 +11,14 @@ public static void main(String[] args) { NumberFormat percentFormatPtBR = NumberFormat.getPercentInstance(new Locale("pt", "BR")); NumberFormat percentFormatEnUS = NumberFormat.getPercentInstance(new Locale("en", "US")); - // String para Percentual + // String to Percent String s = "80,2%"; try { System.out.println("pt_BR: " + percentFormatPtBR.parse(s)); System.out.println("en_US: " + percentFormatEnUS.parse(s)); } catch (ParseException e) { - // trate a exceção de parse + // treat parse exception } // end::code[] } diff --git a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_StringToNumber.java b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_StringToNumber.java index 6ad157b..92125b1 100644 --- a/src/org/j6toj8/localization/formats/numberformat/NumberFormat_StringToNumber.java +++ b/src/org/j6toj8/localization/formats/numberformat/NumberFormat_StringToNumber.java @@ -23,7 +23,7 @@ public static void main(String[] args) { System.out.println("en_US: " + parseEnUS); System.out.println("fr_FR: " + parseFrFR); } catch (ParseException e) { - // trate a exceção no parse + // treat exception in parse } // end::code[] } diff --git a/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Instance.java b/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Instance.java index 1492a07..5d00a65 100644 --- a/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Instance.java +++ b/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Instance.java @@ -11,7 +11,7 @@ public static void main(String[] args) { SimpleDateFormat simpleDate = new SimpleDateFormat("dd MM yy"); SimpleDateFormat simpleTime = new SimpleDateFormat("HH mm ss"); - Date date = new Date(1000000000000L); // data em quantidade de milissegundos desde 01/01/1970 + Date date = new Date(1000000000000L); // date in milliseconds since 01/01/1970 System.out.println(simpleDateTime.format(date)); System.out.println(simpleDate.format(date)); diff --git a/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Parse.java b/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Parse.java index 1464745..d4ce525 100644 --- a/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Parse.java +++ b/src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Parse.java @@ -19,7 +19,7 @@ public static void main(String[] args) { System.out.println(simpleDateTime.parse(dateTime)); System.out.println(simpleDate.parse(date)); System.out.println(simpleTime.parse(time)); - System.out.println(simpleDateTime.parse(time)); // exceção, pois time não tem data + System.out.println(simpleDateTime.parse(time)); // exception because time has no date } catch (ParseException e) { System.out.println(e.getMessage()); } diff --git a/src/org/j6toj8/localization/locale/Locale_Complete.java b/src/org/j6toj8/localization/locale/Locale_Complete.java index 8b06b82..cf616dc 100644 --- a/src/org/j6toj8/localization/locale/Locale_Complete.java +++ b/src/org/j6toj8/localization/locale/Locale_Complete.java @@ -7,11 +7,11 @@ public class Locale_Complete { // tag::code[] public static void main(String[] args) throws IOException { - System.out.println(" - Constantes - "); + System.out.println(" - Constants - "); System.out.println(Locale.CANADA); System.out.println(Locale.UK); - System.out.println(" - Construtor - "); + System.out.println(" - Constructor - "); System.out.println(new Locale("pt", "BR")); System.out.println(new Locale("pt", "PT")); System.out.println(new Locale("ca", "ES", "VALENCIA")); diff --git a/src/org/j6toj8/localization/locale/Locale_LocaleAvailable.java b/src/org/j6toj8/localization/locale/Locale_LocaleAvailable.java index 77f0522..cce9df2 100644 --- a/src/org/j6toj8/localization/locale/Locale_LocaleAvailable.java +++ b/src/org/j6toj8/localization/locale/Locale_LocaleAvailable.java @@ -8,7 +8,7 @@ public class Locale_LocaleAvailable { // tag::code[] public static void main(String[] args) throws IOException { Locale[] availableLocales = Locale.getAvailableLocales(); - // imprime o 10 primeiros Locales disponíveis + // prints the first 10 available locales for (int i = 0; i < 10; i++) { System.out.println(availableLocales[i]); } diff --git a/src/org/j6toj8/localization/locale/Locale_LocaleDefault.java b/src/org/j6toj8/localization/locale/Locale_LocaleDefault.java index 6775fd1..939c6a7 100644 --- a/src/org/j6toj8/localization/locale/Locale_LocaleDefault.java +++ b/src/org/j6toj8/localization/locale/Locale_LocaleDefault.java @@ -7,8 +7,8 @@ public class Locale_LocaleDefault { // tag::code[] public static void main(String[] args) throws IOException { - System.out.println(Locale.getDefault()); // o padrão inicial muda de acordo com seu dispositivo - Locale.setDefault(Locale.KOREA); // altera o Locale default + System.out.println(Locale.getDefault()); // initial default changes according to your device + Locale.setDefault(Locale.KOREA); // change the default Locale System.out.println(Locale.getDefault()); // ko_KR } // end::code[] diff --git a/src/org/j6toj8/localization/locale/Locale_LocaleInstantiation.java b/src/org/j6toj8/localization/locale/Locale_LocaleInstantiation.java index e1763fd..331d9be 100644 --- a/src/org/j6toj8/localization/locale/Locale_LocaleInstantiation.java +++ b/src/org/j6toj8/localization/locale/Locale_LocaleInstantiation.java @@ -7,11 +7,11 @@ public class Locale_LocaleInstantiation { // tag::code[] public static void main(String[] args) throws IOException { - new Locale("pt", "BR"); // pt-BR com Construtor + new Locale("pt", "BR"); // pt-BR with constructor - Locale.forLanguageTag("pt-BR"); // pt-BR com LanguageTag + Locale.forLanguageTag("pt-BR"); // pt-BR with LanguageTag - Locale localePtBR = new Locale.Builder() // pt-BR com Builder + Locale localePtBR = new Locale.Builder() // pt-BR with Builder .setLanguage("pt") .setRegion("BR") .build(); diff --git a/src/org/j6toj8/localization/locale/Locale_LocaleLanguageCountry.java b/src/org/j6toj8/localization/locale/Locale_LocaleLanguageCountry.java index 2c96f37..4242907 100644 --- a/src/org/j6toj8/localization/locale/Locale_LocaleLanguageCountry.java +++ b/src/org/j6toj8/localization/locale/Locale_LocaleLanguageCountry.java @@ -7,10 +7,10 @@ public class Locale_LocaleLanguageCountry { public static void main(String[] args) throws IOException { // tag::code[] - new Locale("pt", "BR"); // Português do Brasil - new Locale("en", "US"); // Inglês dos EUA - new Locale("it", "CH"); // Italiano da Suíça - new Locale("fr", "BE"); // Francês da Bélgica + new Locale("pt", "BR"); // Brazilian Portuguese + new Locale("en", "US"); // US English + new Locale("it", "CH"); // Italian from Switzerland + new Locale("fr", "BE"); // French from Belgium // end::code[] } } diff --git a/src/org/j6toj8/localization/locale/Locale_LocaleLanguageOnly.java b/src/org/j6toj8/localization/locale/Locale_LocaleLanguageOnly.java index f6c15e5..398f38b 100644 --- a/src/org/j6toj8/localization/locale/Locale_LocaleLanguageOnly.java +++ b/src/org/j6toj8/localization/locale/Locale_LocaleLanguageOnly.java @@ -7,10 +7,10 @@ public class Locale_LocaleLanguageOnly { // tag::code[] public static void main(String[] args) throws IOException { - System.out.println(new Locale("pt")); // português - System.out.println(new Locale("en")); // inglês - System.out.println(new Locale("es")); // espanhol - System.out.println(new Locale("fr")); // francês + System.out.println(new Locale("pt")); // portuguese + System.out.println(new Locale("en")); // english + System.out.println(new Locale("es")); // spanish + System.out.println(new Locale("fr")); // french } // end::code[] } diff --git a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Complete.java b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Complete.java index e8d2a32..e26c1a2 100644 --- a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Complete.java +++ b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Complete.java @@ -11,7 +11,7 @@ public static void main(String[] args) { Locale.setDefault(new Locale("en", "US")); - System.out.println("\n -- Locale padrão (en_US) -- "); + System.out.println("\n -- Default Locale (en_US) -- "); ResourceBundle bundleDefault = ResourceBundle.getBundle("Text"); Set keySetDefault = bundleDefault.keySet(); for (String string : keySetDefault) { diff --git a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Inheritance.java b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Inheritance.java index 833dd54..5ec60f5 100644 --- a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Inheritance.java +++ b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_Inheritance.java @@ -8,9 +8,9 @@ public class ResourceBundle_Inheritance { public static void main(String[] args) { // tag::code[] - Locale.setDefault(new Locale("en", "US")); // pt_BR como Locale padrão + Locale.setDefault(new Locale("en", "US")); // pt_BR as default locale ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("pt", "BR")); - System.out.println("Locale: " + bundle.getLocale()); // Bundle localizado para o Locale "pt_BR" (Português do Brasil) + System.out.println("Locale: " + bundle.getLocale()); // Bundle Located for Locale "pt_BR" (Brazilian Portuguese) System.out.println(bundle.getObject("pen")); System.out.println(bundle.getObject("paper")); System.out.println(bundle.getObject("keyboard")); diff --git a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java index 75db55e..3c5b4dc 100644 --- a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java +++ b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java @@ -9,8 +9,8 @@ public static void main(String[] args) { // tag::code[] /* - * Recupera o Bundle do arquivo "Text_fr_CA.java", - * pois tem precedência sobre o arquivo "Text_fr_CA.properties" + * Retrieves the bundle from the file "Text_fr_CA.java", + * as it takes precedence over the file "Text_fr_CA.properties" */ ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("fr", "CA")); System.out.println(bundle.getString("pen")); diff --git a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_KeysProgrammatically.java b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_KeysProgrammatically.java index 0320e98..e4ab76e 100644 --- a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_KeysProgrammatically.java +++ b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_KeysProgrammatically.java @@ -9,12 +9,12 @@ public class ResourceBundle_KeysProgrammatically { // tag::code[] public static void main(String[] args) { - Locale.setDefault(new Locale("en", "US")); // Coloca o Locale en_US como padrão + Locale.setDefault(new Locale("en", "US")); // Set Locale en_US as default - ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("pt", "BR")); // Recupera o bundle 'Text' para o Locale pt_BR - Set keySet = bundle.keySet(); // Pega um Set com todas as chaves + ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("pt", "BR")); // Retrieve 'Text' bundle for Locale pt_BR + Set keySet = bundle.keySet(); // Get a set with all the keys for (String key : keySet) { - System.out.println(key + " - " + bundle.getString(key)); // Imprime " - " + System.out.println(key + " - " + bundle.getString(key)); // Print " - " } } diff --git a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_NotExactLocale.java b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_NotExactLocale.java index 0769ce2..6175655 100644 --- a/src/org/j6toj8/localization/resourcebundle/ResourceBundle_NotExactLocale.java +++ b/src/org/j6toj8/localization/resourcebundle/ResourceBundle_NotExactLocale.java @@ -8,11 +8,11 @@ public class ResourceBundle_NotExactLocale { public static void main(String[] args) { // tag::code[] - Locale.setDefault(new Locale("pt", "BR")); // pt_BR como Locale padrão + Locale.setDefault(new Locale("pt", "BR")); // pt_BR as default Locale ResourceBundle bundle2 = ResourceBundle.getBundle("Text", new Locale("zh", "CN")); - System.out.println(bundle2.getLocale()); // Bundle localizado para o Locale "zh_CH" (Chinês simplificado) + System.out.println(bundle2.getLocale()); // Bundle located for Locale "zh_CN" (Simplified Chinese) ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("it", "CH")); - System.out.println(bundle.getLocale()); // Bundle localizado para o Locale "it_CH" (Italiano da Suíça) + System.out.println(bundle.getLocale()); // Bundle located for Locale "it_CH" (Italian from Switzerland) // end::code[] } diff --git a/src/org/j6toj8/localization/timezones/ZonedDateTime_Constructor.java b/src/org/j6toj8/localization/timezones/ZonedDateTime_Constructor.java index 347a1d1..491445e 100644 --- a/src/org/j6toj8/localization/timezones/ZonedDateTime_Constructor.java +++ b/src/org/j6toj8/localization/timezones/ZonedDateTime_Constructor.java @@ -6,7 +6,7 @@ public class ZonedDateTime_Constructor { public static void main(String[] args) { // tag::code[] - ZonedDateTime zonedDateTime = new ZonedDateTime(); // NÃO COMPILA! - não possui construtor público + ZonedDateTime zonedDateTime = new ZonedDateTime(); // NOT COMPILING! - doesn't have a public constructor System.out.println(zonedDateTime); // end::code[] } diff --git a/src/org/j6toj8/localization/timezones/ZonedDateTime_DaylightSavings.java b/src/org/j6toj8/localization/timezones/ZonedDateTime_DaylightSavings.java index 1ddc224..0c17e36 100644 --- a/src/org/j6toj8/localization/timezones/ZonedDateTime_DaylightSavings.java +++ b/src/org/j6toj8/localization/timezones/ZonedDateTime_DaylightSavings.java @@ -9,7 +9,7 @@ public static void main(String[] args) { // tag::code[] ZonedDateTime zonedDateTime = ZonedDateTime.of(2018, 11, 3, 23, 30, 0, 0, ZoneId.of("America/Sao_Paulo")); System.out.println(zonedDateTime); - System.out.println("+2 horas: " + zonedDateTime.plusHours(2)); + System.out.println("+2 hours: " + zonedDateTime.plusHours(2)); // end::code[] } } diff --git a/src/org/j6toj8/localization/timezones/ZonedDateTime_Immutability.java b/src/org/j6toj8/localization/timezones/ZonedDateTime_Immutability.java index 5e78ea5..2bccc67 100644 --- a/src/org/j6toj8/localization/timezones/ZonedDateTime_Immutability.java +++ b/src/org/j6toj8/localization/timezones/ZonedDateTime_Immutability.java @@ -9,9 +9,9 @@ public static void main(String[] args) { // tag::code[] ZonedDateTime zonedDateTime = ZonedDateTime.of(2019, 5, 20, 9, 20, 3, 300, ZoneId.of("America/Sao_Paulo")); System.out.println(zonedDateTime); - zonedDateTime.plusHours(1); // chamada perdida - a nova data/hora não foi armazenada em uma variável + zonedDateTime.plusHours(1); // missed call - new date/time was not stored in a variable System.out.println(zonedDateTime); - zonedDateTime = zonedDateTime.plusHours(1); // chamada útil - data/hora armazenada na variável + zonedDateTime = zonedDateTime.plusHours(1); // useful call - date/time stored in variable System.out.println(zonedDateTime); // end::code[] } diff --git a/src/org/j6toj8/localization/timezones/ZonedDateTime_Invalid.java b/src/org/j6toj8/localization/timezones/ZonedDateTime_Invalid.java index b053aa3..45c60e4 100644 --- a/src/org/j6toj8/localization/timezones/ZonedDateTime_Invalid.java +++ b/src/org/j6toj8/localization/timezones/ZonedDateTime_Invalid.java @@ -7,7 +7,7 @@ public class ZonedDateTime_Invalid { public static void main(String[] args) { // tag::code[] - System.out.println(ZonedDateTime.of(2019, 4, 31, 9, 20, 3, 1000, ZoneId.of("America/Sao_Paulo"))); // lança exceção: não existe 31 de abril + System.out.println(ZonedDateTime.of(2019, 4, 31, 9, 20, 3, 1000, ZoneId.of("America/Sao_Paulo"))); // throws exception: there is no April 31 // end::code[] } } diff --git a/src/org/j6toj8/localization/timezones/ZonedDateTime_Manipulate.java b/src/org/j6toj8/localization/timezones/ZonedDateTime_Manipulate.java index 6071a7e..1e231ea 100644 --- a/src/org/j6toj8/localization/timezones/ZonedDateTime_Manipulate.java +++ b/src/org/j6toj8/localization/timezones/ZonedDateTime_Manipulate.java @@ -10,29 +10,28 @@ public static void main(String[] args) { // tag::code[] ZonedDateTime zonedDateTime = ZonedDateTime.of(2019, 5, 20, 9, 20, 12, 1000, ZoneId.of("America/Sao_Paulo")); System.out.println(zonedDateTime); - System.out.println("+2 horas: " + zonedDateTime.plusHours(2)); - System.out.println("+2 minutos: " + zonedDateTime.plusMinutes(2)); - System.out.println("+2 segundos: " + zonedDateTime.plusSeconds(2)); - System.out.println("+2 nanosegundos: " + zonedDateTime.plusNanos(2)); - System.out.println("+2 microssegundos: " + zonedDateTime.plus(2, ChronoUnit.MICROS)); - System.out.println("+2 milissegundos: " + zonedDateTime.plus(2, ChronoUnit.MILLIS)); - System.out.println("-2 horas: " + zonedDateTime.minusHours(2)); - System.out.println("-2 minutos: " + zonedDateTime.minusMinutes(2)); - System.out.println("-2 segundos: " + zonedDateTime.minusSeconds(2)); - System.out.println("-2 nanosegundos: " + zonedDateTime.minusNanos(2)); - System.out.println("-2 microssegundos: " + zonedDateTime.minus(2, ChronoUnit.MICROS)); - System.out.println("-2 milissegundos: " + zonedDateTime.minus(2, ChronoUnit.MILLIS)); - System.out.println("+2 dias: " + zonedDateTime.plusDays(2)); - System.out.println("+2 semanas: " + zonedDateTime.plusWeeks(2)); - System.out.println("+2 meses: " + zonedDateTime.plusMonths(2)); - System.out.println("+2 anos: " + zonedDateTime.plusYears(2)); - System.out.println("+2 anos: " + zonedDateTime.plusYears(2)); - System.out.println("+2 décadas: " + zonedDateTime.plus(2, ChronoUnit.DECADES)); - System.out.println("-2 dias: " + zonedDateTime.minusDays(2)); - System.out.println("-2 semanas: " + zonedDateTime.minusWeeks(2)); - System.out.println("-2 meses: " + zonedDateTime.minusMonths(2)); - System.out.println("-2 anos: " + zonedDateTime.minusYears(2)); - System.out.println("-2 décadas: " + zonedDateTime.minus(2, ChronoUnit.DECADES)); + System.out.println("+2 hours: " + zonedDateTime.plusHours(2)); + System.out.println("+2 minutes: " + zonedDateTime.plusMinutes(2)); + System.out.println("+2 seconds: " + zonedDateTime.plusSeconds(2)); + System.out.println("+2 nanoseconds: " + zonedDateTime.plusNanos(2)); + System.out.println("+2 microseconds: " + zonedDateTime.plus(2, ChronoUnit.MICROS)); + System.out.println("+2 milliseconds: " + zonedDateTime.plus(2, ChronoUnit.MILLIS)); + System.out.println("-2 hours: " + zonedDateTime.minusHours(2)); + System.out.println("-2 minutes: " + zonedDateTime.minusMinutes(2)); + System.out.println("-2 seconds: " + zonedDateTime.minusSeconds(2)); + System.out.println("-2 nanoseconds: " + zonedDateTime.minusNanos(2)); + System.out.println("-2 microseconds: " + zonedDateTime.minus(2, ChronoUnit.MICROS)); + System.out.println("-2 milliseconds: " + zonedDateTime.minus(2, ChronoUnit.MILLIS)); + System.out.println("+2 days: " + zonedDateTime.plusDays(2)); + System.out.println("+2 weeks: " + zonedDateTime.plusWeeks(2)); + System.out.println("+2 months: " + zonedDateTime.plusMonths(2)); + System.out.println("+2 years: " + zonedDateTime.plusYears(2)); + System.out.println("+2 decades: " + zonedDateTime.plus(2, ChronoUnit.DECADES)); + System.out.println("-2 days: " + zonedDateTime.minusDays(2)); + System.out.println("-2 weeks: " + zonedDateTime.minusWeeks(2)); + System.out.println("-2 months: " + zonedDateTime.minusMonths(2)); + System.out.println("-2 years: " + zonedDateTime.minusYears(2)); + System.out.println("-2 decades: " + zonedDateTime.minus(2, ChronoUnit.DECADES)); // end::code[] } } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_Parallel.java b/src/org/j6toj8/streams/parallelstreams/Streams_Parallel.java index d890a69..882174f 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_Parallel.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_Parallel.java @@ -8,7 +8,7 @@ public static void main(String[] args) { // tag::code[] String[] array = new String[] { "A", "B", "C" }; Arrays.stream(array) - .parallel() // stream transformado em paralelo + .parallel() // stream transformed in parallel .forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelFindAny.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelFindAny.java index fe03588..6c5c80d 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelFindAny.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelFindAny.java @@ -9,12 +9,12 @@ public static void main(String[] args) { // tag::code[] Optional findAny1 = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) .findFirst(); - System.out.println("findAny Sequencial: " + findAny1.get()); + System.out.println("findAny Sequential: " + findAny1.get()); Optional findAny2 = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) .parallel() .findAny(); - System.out.println("findAny Paralelo: " + findAny2.get()); + System.out.println("findAny Parallel: " + findAny2.get()); // end::code[] } } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEach.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEach.java index 5021cc7..1ee0d52 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEach.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEach.java @@ -9,12 +9,12 @@ public static void main(String[] args) { // tag::code[] List list = Arrays.asList("A", "B", "C"); - System.out.println("Sequencial: "); - list.stream() // cria um Stream sequencial + System.out.println("Sequential: "); + list.stream() // create a sequential stream .forEach(System.out::println); - System.out.println("Paralelo: "); - list.parallelStream() // cria um Stream paralelo + System.out.println("Parallel: "); + list.parallelStream() // create a parallel stream .forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEachOrdered.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEachOrdered.java index 76ac03d..3a45d2a 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEachOrdered.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEachOrdered.java @@ -9,12 +9,12 @@ public static void main(String[] args) { // tag::code[] List list = Arrays.asList("A", "B", "C"); - System.out.println("Sequencial: "); - list.stream() // cria um Stream sequencial + System.out.println("Sequential: "); + list.stream() // create a sequential stream .forEachOrdered(System.out::println); - System.out.println("Paralelo: "); - list.parallelStream() // cria um Stream paralelo + System.out.println("Parallel: "); + list.parallelStream() // create a parallel stream .forEachOrdered(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelPerformance.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelPerformance.java index 1e84fb2..dc7991b 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelPerformance.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelPerformance.java @@ -6,18 +6,18 @@ public class Streams_ParallelPerformance { public static void main(String[] args) { // tag::code[] - long inicio = System.currentTimeMillis(); - IntStream.range(0, Integer.MAX_VALUE) // stream sequencial + long start = System.currentTimeMillis(); + IntStream.range(0, Integer.MAX_VALUE) // sequential stream .mapToDouble(n -> Math.pow(n, 2)) .average() - .ifPresent(n -> System.out.println("Tempo stream sequencial: " + (System.currentTimeMillis() - inicio))); + .ifPresent(n -> System.out.println("Sequential Stream time: " + (System.currentTimeMillis() - start))); - long inicio2 = System.currentTimeMillis(); + long start2 = System.currentTimeMillis(); IntStream.range(0, Integer.MAX_VALUE) - .parallel() // stream paralelo + .parallel() // parallel stream .mapToDouble(n -> Math.pow(n, 2)) .average() - .ifPresent(n -> System.out.println("Tempo stream paralelo: " + (System.currentTimeMillis() - inicio2))); + .ifPresent(n -> System.out.println("Parallel Stream time: " + (System.currentTimeMillis() - start2))); // end::code[] } } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStatefulOperation.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStatefulOperation.java index 66fdc5e..1adff81 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStatefulOperation.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStatefulOperation.java @@ -12,12 +12,12 @@ public static void main(String[] args) { List synchronizedList = Collections.synchronizedList(new ArrayList<>()); List list = Arrays.asList("A", "B", "C"); - System.out.println("Ordem no forEachOrdered: "); + System.out.println("Order on forEachOrdered: "); list.parallelStream() - .map(s -> {synchronizedList.add(s); return s;}) // operação com efeito colateral - altera o estado de um objeto + .map(s -> {synchronizedList.add(s); return s;}) // side effect operation - changes the state of an object .forEachOrdered(System.out::println); - System.out.println("Ordem na synchronizedList: "); + System.out.println("Order on synchronizedList: "); for (String s : synchronizedList) { System.out.println(s); } diff --git a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStream.java b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStream.java index 88b82d1..5821d15 100644 --- a/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStream.java +++ b/src/org/j6toj8/streams/parallelstreams/Streams_ParallelStream.java @@ -8,7 +8,7 @@ public class Streams_ParallelStream { public static void main(String[] args) { // tag::code[] List list = Arrays.asList("A", "B", "C"); - list.parallelStream() // cria um Stream paralelo diretamente + list.parallelStream() // create a parallel stream directly .forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_ArraysStream.java b/src/org/j6toj8/streams/usingstreams/Streams_ArraysStream.java index 6883c92..faf96c9 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_ArraysStream.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_ArraysStream.java @@ -6,10 +6,9 @@ public class Streams_ArraysStream { public static void main(String[] args) { // tag::code[] - // Criação de um array comum de Strings + // Create a common string array String[] array = new String[] { "A", "B", "C" }; - // Criação de um Stream a partir do array e, para - // cada elemento, o método println é chamado. + // Create a stream from the array and, for each element, the println method is called. Arrays.stream(array).forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Distinct.java b/src/org/j6toj8/streams/usingstreams/Streams_Distinct.java index c80bd70..42886ca 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Distinct.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Distinct.java @@ -6,11 +6,11 @@ public class Streams_Distinct { public static void main(String[] args) { // tag::code[] - // Criação de um array comum de Strings + // Create a common string array String[] array = new String[] { "A", "B", "C", "A", "B", "F" }; Arrays.stream(array) - .distinct() // ignora elementos repetidos + .distinct() // ignore repeated elements .forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Filter.java b/src/org/j6toj8/streams/usingstreams/Streams_Filter.java index fcc0877..8e9df86 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Filter.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Filter.java @@ -6,9 +6,9 @@ public class Streams_Filter { public static void main(String[] args) { // tag::code[] - IntStream.range(0, 4) // stream de 0 a 3 - .filter(e -> e % 2 == 0) // limita a números pares (resto da divisão por 2 é 0) - .forEach(System.out::println); // imprime os elementos + IntStream.range(0, 4) // stream from 0 to 3 + .filter(e -> e % 2 == 0) // limited to even numbers (rest of division by 2 is 0) + .forEach(System.out::println); // prints the elements // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_FindFirstAny.java b/src/org/j6toj8/streams/usingstreams/Streams_FindFirstAny.java index b5537aa..3393f7a 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_FindFirstAny.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_FindFirstAny.java @@ -7,12 +7,12 @@ public class Streams_FindFirstAny { public static void main(String[] args) { // tag::code[] - Optional findFirst = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .findFirst(); // pega o primeiro número do Stream + Optional findFirst = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .findFirst(); // get the first stream number System.out.println("First: " + findFirst.get()); - Optional findAny = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .findAny(); // pega qualquer número do Stream + Optional findAny = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .findAny(); // get any number from the stream System.out.println("Any: " + findAny.get()); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_FlatMap.java b/src/org/j6toj8/streams/usingstreams/Streams_FlatMap.java index d102728..a8d5ea7 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_FlatMap.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_FlatMap.java @@ -7,14 +7,14 @@ public class Streams_FlatMap { public static void main(String[] args) { // tag::code[] - // Criação de 3 arrays distintos + // Create 3 distinct arrays String[] array1 = new String[] { "A", "B", "C" }; String[] array2 = new String[] { "D", "E", "F" }; String[] array3 = new String[] { "G", "H", "I" }; - Stream.of(array1, array2, array3) // criação de um Stream de Arrays - .flatMap(a -> Arrays.stream(a)) // transforma os dados de cada array em um único fluxo de dados - .forEach(System.out::println); // imprime os elementos + Stream.of(array1, array2, array3) // create a stream of arrays + .flatMap(a -> Arrays.stream(a)) // transform data from each array into a single data stream + .forEach(System.out::println); // prints the elements // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Limit.java b/src/org/j6toj8/streams/usingstreams/Streams_Limit.java index 32ea087..f688f78 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Limit.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Limit.java @@ -6,9 +6,9 @@ public class Streams_Limit { public static void main(String[] args) { // tag::code[] - IntStream.range(0, 4) // stream de 0 a 3 - .limit(2) // limita a 2 elementos - .forEach(System.out::println); // imprime os elementos + IntStream.range(0, 4) // stream from 0 to 3 + .limit(2) // limited to 2 elements + .forEach(System.out::println); // prints the elements // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Map.java b/src/org/j6toj8/streams/usingstreams/Streams_Map.java index b21907e..14c1fdf 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Map.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Map.java @@ -6,9 +6,9 @@ public class Streams_Map { public static void main(String[] args) { // tag::code[] - IntStream.range(0, 4) // stream de 0 a 3 - .map(e -> e * 2) // multiplica os elementos por 2 - .forEach(System.out::println); // imprime os elementos + IntStream.range(0, 4) // stream from 0 to 3 + .map(e -> e * 2) // multiply the elements by 2 + .forEach(System.out::println); // prints the elements // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Match.java b/src/org/j6toj8/streams/usingstreams/Streams_Match.java index de68a63..a79fbad 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Match.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Match.java @@ -6,16 +6,16 @@ public class Streams_Match { public static void main(String[] args) { // tag::code[] - boolean anyMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .anyMatch(e -> e > 5); // vefifica se algum elemento é maior que 5 + boolean anyMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .anyMatch(e -> e > 5); // check if any element is greater than 5 System.out.println("anyMatch: " + anyMatch); - boolean allMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .allMatch(e -> e > 5); // vefifica se TODOS os elementos são maiores que 5 + boolean allMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .allMatch(e -> e > 5); // check if ALL elements are greater than 5 System.out.println("allMatch: " + allMatch); - boolean noneMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .noneMatch(e -> e > 5); // vefifica NENHUM elemento é maior que 5 + boolean noneMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .noneMatch(e -> e > 5); // checks that NO element is greater than 5 System.out.println("noneMatch: " + noneMatch); // end::code[] diff --git a/src/org/j6toj8/streams/usingstreams/Streams_MaxMinCount.java b/src/org/j6toj8/streams/usingstreams/Streams_MaxMinCount.java index 03ef1ea..3e8e436 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_MaxMinCount.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_MaxMinCount.java @@ -8,16 +8,16 @@ public class Streams_MaxMinCount { public static void main(String[] args) { // tag::code[] - Optional max = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .max(Comparator.naturalOrder()); // pega o maior número do Stream + Optional max = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .max(Comparator.naturalOrder()); // get the greatest stream number System.out.println("Max: " + max.get()); - Optional min = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .min(Comparator.naturalOrder()); // pega o menor número do Stream + Optional min = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .min(Comparator.naturalOrder()); // get the smallest stream number System.out.println("Min: " + min.get()); - long count = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer - .count(); // pega a quantidade de elementos do Stream + long count = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream from multiple Integer + .count(); // get the number of stream elements System.out.println("Count: " + count); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Optional.java b/src/org/j6toj8/streams/usingstreams/Streams_Optional.java index 3d70234..e4ea92f 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Optional.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Optional.java @@ -8,13 +8,13 @@ public class Streams_Optional { public static void main(String[] args) { // tag::code[] - // Exemplo sem encadear a chamada de Optional + // Example without Chaining Optional Calling Optional max = Stream.of(7, 2, 1) .max(Comparator.naturalOrder()); max.ifPresent(System.out::println); - // Exemplo encadeando a chamada de Optional + // Example by Chaining Optional Calling Stream.of(7, 2, 1) .max(Comparator.naturalOrder()) .ifPresent(System.out::println); diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Peek.java b/src/org/j6toj8/streams/usingstreams/Streams_Peek.java index bb9288c..70f09f5 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Peek.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Peek.java @@ -6,11 +6,11 @@ public class Streams_Peek { public static void main(String[] args) { // tag::code[] - // Criação de um array comum de Strings + // Create a common string array String[] array = new String[] { "G", "T", "Y", "A" }; Arrays.stream(array) - .peek(e -> System.out.println("Peek: " + e)) // observa o que passou pelo Stream + .peek(e -> System.out.println("Peek: " + e)) // watch what went through the stream .forEach(e -> System.out.println("ForEach: " + e)); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Pipeline.java b/src/org/j6toj8/streams/usingstreams/Streams_Pipeline.java index 006bb22..a04a79b 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Pipeline.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Pipeline.java @@ -6,12 +6,12 @@ public class Streams_Pipeline { public static void main(String[] args) { // tag::code[] - IntStream.range(0, 10) // Stream de 0 a 9 - .filter(e -> e % 2 == 0) // mantém apenas números pares - .skip(2) // ignora os dois primeiros - .limit(2) // limita a 3 elementos - .map(e -> e * 2) // multipla cada elemento por 2 - .forEach(System.out::println); // imprime cada elemento + IntStream.range(0, 10) // 0 to 9 Stream + .filter(e -> e % 2 == 0) // keep only even numbers + .skip(2) // ignore the first two + .limit(2) // limited to 3 elements + .map(e -> e * 2) // multiply each element by 2 + .forEach(System.out::println); // print each element // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_ReuseStream.java b/src/org/j6toj8/streams/usingstreams/Streams_ReuseStream.java index 93b09e9..9ba171b 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_ReuseStream.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_ReuseStream.java @@ -7,8 +7,8 @@ public class Streams_ReuseStream { public static void main(String[] args) { // tag::code[] Stream stream = Stream.of(7, 2, 1); - stream.forEach(System.out::println); // imprime elementos do Stream - stream.forEach(System.out::println); // LANÇA EXCEÇÃO - o Stream já estava fechado + stream.forEach(System.out::println); // print stream elements + stream.forEach(System.out::println); // THROWS EXCEPTION - Stream was already closed // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Skip.java b/src/org/j6toj8/streams/usingstreams/Streams_Skip.java index 486585f..16db599 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Skip.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Skip.java @@ -6,9 +6,9 @@ public class Streams_Skip { public static void main(String[] args) { // tag::code[] - IntStream.range(0, 4) // stream de 0 a 3 - .skip(2) // ignora 2 elementos - .forEach(System.out::println); // imprime os elementos + IntStream.range(0, 4) // stream from 0 to 3 + .skip(2) // ignore 2 elements + .forEach(System.out::println); // prints the elements // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/Streams_Sorted.java b/src/org/j6toj8/streams/usingstreams/Streams_Sorted.java index a80de78..444ecb7 100644 --- a/src/org/j6toj8/streams/usingstreams/Streams_Sorted.java +++ b/src/org/j6toj8/streams/usingstreams/Streams_Sorted.java @@ -6,11 +6,11 @@ public class Streams_Sorted { public static void main(String[] args) { // tag::code[] - // Criação de um array comum de Strings + // Create a common string array String[] array = new String[] { "G", "T", "Y", "A", "B", "C", "A", "B", "F" }; Arrays.stream(array) - .sorted() // ordena utilizando a ordem natural + .sorted() // orders using the natural order .forEach(System.out::println); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorAveragingInt.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorAveragingInt.java index bb47546..c1dbc73 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorAveragingInt.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorAveragingInt.java @@ -7,7 +7,7 @@ public class Streams_CollectorAveragingInt { public static void main(String[] args) { // tag::code[] - // Calcula a média do tamanho de cada nome + // Calculate the average length of each name Double collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.averagingInt(s -> s.length())); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingBy.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingBy.java index 7e15dac..e7c7ce3 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingBy.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingBy.java @@ -9,9 +9,9 @@ public class Streams_CollectorGroupingBy { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o tamanho do nome - // O Valor é uma lista com os nomes que tem aquele tamanho + // Store the result of the stream in a map + // The key is the name length + // Value is a list of names that are that long Map> collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.groupingBy(s -> s.length())); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByDownstream.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByDownstream.java index b210626..53344c5 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByDownstream.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByDownstream.java @@ -8,9 +8,9 @@ public class Streams_CollectorGroupingByDownstream { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o tamanho do nome - // O Valor são os nomes que tem aquele tamanho + // Store the result of the stream in a map + // The key is the name length + // Value is the names that have that size Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.groupingBy(s -> s.length(), Collectors.joining(","))); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java index 3b3cbea..fd3db53 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java @@ -9,9 +9,9 @@ public class Streams_CollectorGroupingByMapFactory { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o tamanho do nome - // O Valor são os nomes que tem aquele tamanho + // Store the result of the stream in a map + // The key is the name length + // Value is the names that have that size Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.groupingBy(s -> s.length(), TreeMap::new, Collectors.joining(","))); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorMapping.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorMapping.java index f407297..7a30634 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorMapping.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorMapping.java @@ -8,9 +8,9 @@ public class Streams_CollectorMapping { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o tamanho do nome - // O Valor são os nomes que tem aquele tamanho, convertidos para maiúscula, separados por vírgula + // Store the result of the stream in a map + // The key is the name length + // The Value is the names with that size, converted to uppercase, separated by comma Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.groupingBy(s -> s.length(), Collectors.mapping(s -> s.toUpperCase(), Collectors.joining(",")))); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningBy.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningBy.java index 84fda55..b188419 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningBy.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningBy.java @@ -9,9 +9,9 @@ public class Streams_CollectorPartitioningBy { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // As Chaves são true ou false - // O Valor é uma lista dos valores que atendem ou não a regra de particionamento + // Store the result of the stream in a map + // Keys are true or false + // Value is a list of values that meet or not the partitioning rule Map> collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.partitioningBy(s -> s.startsWith("R"))); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java index af8f0ef..5903884 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java @@ -8,9 +8,9 @@ public class Streams_CollectorPartitioningByDownstream { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // As Chaves são true ou false - // O Valor é uma String que são os nomes que atendem ou não a regra de particionamento + // Store the result of the stream in a map + // Keys are true or false + // Value is a String which are the names that meet or not the partitioning rule. Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.partitioningBy(s -> s.startsWith("R"), Collectors.joining(","))); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToCollect.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToCollect.java index 135cf75..ba2a946 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToCollect.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToCollect.java @@ -12,22 +12,22 @@ public class Streams_CollectorToCollect { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um ArrayList + // store Stream result in an ArrayList Collection collect = Stream.of(1, 2, 3, 4) .collect(Collectors.toCollection(ArrayList::new)); System.out.println("ArrayList: " + collect); - // Armazena o resultado do Stream em um HashSet + // store Stream result in a HashSet Collection collect2 = Stream.of(1, 2, 3, 4) .collect(Collectors.toCollection(HashSet::new)); System.out.println("HashSet: " + collect2); - // Armazena o resultado do Stream em uma LinkedList + // store Stream result in a LinkedList Collection collect3 = Stream.of(1, 2, 3, 4) .collect(Collectors.toCollection(LinkedList::new)); System.out.println("LinkedList: " + collect3); - // Armazena o resultado do Stream em um TreeSet + // store Stream result in a TreeSet Collection collect4 = Stream.of(1, 2, 3, 4) .collect(Collectors.toCollection(TreeSet::new)); System.out.println("TreeSet: " + collect4); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMap.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMap.java index 0bea4d9..7e26100 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMap.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMap.java @@ -8,9 +8,9 @@ public class Streams_CollectorToMap { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o próprio nome (s -> s) - // O Valor é o tamanho do nome + // Store the result of the stream in a map + // The key is its own name (s -> s) + // Value is the name length Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.toMap(s -> s, s -> s.length())); diff --git a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java index 9e74a47..1f22ed5 100644 --- a/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java +++ b/src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java @@ -8,9 +8,9 @@ public class Streams_CollectorToMapDuplicateKey { public static void main(String[] args) { // tag::code[] - // Armazena o resultado do Stream em um Mapa - // A Chave é o tamanho do nome - // O Valor são os nomes com aquele tamanho + // Store the result of the stream in a map + // The key is the name length + // Value is the names with that size Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") .collect(Collectors.toMap(s -> s.length(), s -> s, (s1, s2) -> s1 + "," + s2)); diff --git a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Generate.java b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Generate.java index cbeef86..3bbe245 100644 --- a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Generate.java +++ b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Generate.java @@ -8,13 +8,13 @@ public class Streams_Generate { public static void main(String[] args) { // tag::code[] - // Cria Stream infinito de números aleatórios - System.out.println(" IntStream infinito de números aleatórios"); + // Create infinite stream of random numbers + System.out.println(" infinity IntStream of random numbers"); IntStream.generate(() -> new Random().nextInt()) .limit(3) .forEach(System.out::println); - System.out.println("\n DoubleStream infinito de números aleatórios"); + System.out.println("\n infinity DoubleStream of random numbers"); DoubleStream.generate(Math::random) .limit(3) .forEach(System.out::println); diff --git a/src/org/j6toj8/streams/usingstreams/primitives/Streams_MapTo.java b/src/org/j6toj8/streams/usingstreams/primitives/Streams_MapTo.java index 00aa8ae..354a578 100644 --- a/src/org/j6toj8/streams/usingstreams/primitives/Streams_MapTo.java +++ b/src/org/j6toj8/streams/usingstreams/primitives/Streams_MapTo.java @@ -9,19 +9,19 @@ public static void main(String[] args) { // tag::code[] List list = Arrays.asList(1, 2, 3, 4); - System.out.println(" Stream para IntStream"); - list.stream() // cria Stream - .mapToInt(Integer::intValue) // transforma em IntStream + System.out.println(" Stream to IntStream"); + list.stream() // creates Stream + .mapToInt(Integer::intValue) // transform into IntStream .forEach(System.out::print); - System.out.println("\n Stream para LongStream"); - list.stream() // cria Stream - .mapToLong(Integer::longValue) // transforma em LongStream + System.out.println("\n Stream to LongStream"); + list.stream() // creates Stream + .mapToLong(Integer::longValue) // transform into LongStream .forEach(System.out::print); - System.out.println("\n Stream para DoubleStream"); - list.stream() // cria Stream - .mapToDouble(Integer::doubleValue) // transforma em DoubleStream + System.out.println("\n Stream to DoubleStream"); + list.stream() // creates Stream + .mapToDouble(Integer::doubleValue) // transform into DoubleStream .forEach(System.out::print); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Primitives.java b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Primitives.java index f70f13d..ce0f9f4 100644 --- a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Primitives.java +++ b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Primitives.java @@ -18,7 +18,7 @@ public static void main(String[] args) { System.out.println("\n LongStream"); LongStream.of(1, 2, 3).forEach(System.out::print); - System.out.println(""); + System.out.println(); LongStream.range(1, 4).forEach(System.out::print); // end::code[] } diff --git a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Statistics.java b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Statistics.java index 9738c9d..a42d7f5 100644 --- a/src/org/j6toj8/streams/usingstreams/primitives/Streams_Statistics.java +++ b/src/org/j6toj8/streams/usingstreams/primitives/Streams_Statistics.java @@ -8,11 +8,11 @@ public class Streams_Statistics { public static void main(String[] args) { // tag::code[] IntSummaryStatistics summaryStatistics = IntStream.range(0, 10).summaryStatistics(); - System.out.println("Quantidade: " + summaryStatistics.getCount()); - System.out.println("Maior: " + summaryStatistics.getMax()); - System.out.println("Menor: " + summaryStatistics.getMin()); - System.out.println("Soma: " + summaryStatistics.getSum()); - System.out.println("Média: " + summaryStatistics.getAverage()); + System.out.println("Count: " + summaryStatistics.getCount()); + System.out.println("Max: " + summaryStatistics.getMax()); + System.out.println("Min: " + summaryStatistics.getMin()); + System.out.println("Sum: " + summaryStatistics.getSum()); + System.out.println("Average: " + summaryStatistics.getAverage()); // end::code[] } } diff --git a/src/org/j6toj8/streams/usingstreams/reduce/Streams_Reduce.java b/src/org/j6toj8/streams/usingstreams/reduce/Streams_Reduce.java index b49be21..336881f 100644 --- a/src/org/j6toj8/streams/usingstreams/reduce/Streams_Reduce.java +++ b/src/org/j6toj8/streams/usingstreams/reduce/Streams_Reduce.java @@ -8,7 +8,7 @@ public class Streams_Reduce { public static void main(String[] args) { // tag::code[] Optional reduce = Stream.of(7, 2, 3, 8) - .reduce((e1, e2) -> e1 * e2); // reduce que multiplica todos os números + .reduce((e1, e2) -> e1 * e2); // reduce that multiplies all numbers System.out.println(reduce.get()); // end::code[]