├── .gitattributes ├── .gitignore ├── .idea └── compiler.xml ├── .npmrc ├── .releaserc ├── .travis.yml ├── A-tricks-to-succeed.asc ├── B-test-yourself.asc ├── C-references.asc ├── CHANGELOG.md ├── LICENSE.asc ├── README.asc ├── book ├── 01-getting-started │ └── sections │ │ ├── 01-introduction.asc │ │ └── 02-objectives.asc ├── 02-language-enhancement │ └── sections │ │ ├── 01-string-in-switch-and-literals.asc │ │ ├── 02-try-with-resources.asc │ │ ├── 03-multiple-exception.asc │ │ └── 04-static-default-in-interfaces.asc ├── 03-localization │ └── sections │ │ ├── 01-locale.asc │ │ ├── 02-resource-bundle.asc │ │ ├── 03-date-time.asc │ │ ├── 04-formats.asc │ │ └── 05-time-zones.asc ├── 04-lambda │ └── sections │ │ ├── 01-functional-interfaces.asc │ │ ├── 02-lambda-expression.asc │ │ ├── 03-built-in-interfaces.asc │ │ └── 04-method-reference.asc ├── 05-java-streams │ └── sections │ │ ├── 01-using-streams.asc │ │ └── 02-parallel-streams.asc ├── 06-concurrency │ └── sections │ │ ├── 01-concurrent-package.asc │ │ ├── 02-locks.asc │ │ ├── 03-execute-tasks.asc │ │ └── 04-fork-join.asc ├── 07-file-io │ └── sections │ │ ├── 01-paths.asc │ │ ├── 02-files.asc │ │ ├── 03-recursive-access.asc │ │ ├── 04-file-improvements.asc │ │ └── 05-watch-service.asc ├── 08-java-collections │ └── sections │ │ ├── 01-diamond.asc │ │ ├── 02-collections-lambda.asc │ │ ├── 03-data-search.asc │ │ ├── 04-calculations.asc │ │ ├── 05-collection-improvements.asc │ │ └── 06-merge-map.asc ├── contributors.asc └── license.asc ├── ch01-getting-started.asc ├── ch02-language-enhancement.asc ├── ch03-localization.asc ├── ch04-lambda.asc ├── ch05-java-streams.asc ├── ch06-concurrency.asc ├── ch07-java-file-io.asc ├── ch08-java-collections.asc ├── ch09-assume.asc ├── changelog.config.js ├── docker-compose.yml ├── docker └── travis │ └── Dockerfile ├── images ├── cover.png └── ebook-400x400.png ├── java6-to-java8.asc ├── package.json ├── resources ├── Text.properties ├── Text_es.properties ├── Text_es_ES.properties ├── Text_fr_CA.java ├── Text_fr_CA.properties ├── Text_fr_FR.java ├── Text_it.properties ├── Text_pt.properties └── Text_pt_BR.properties ├── scripts └── docker-startup.sh └── src └── org └── j6toj8 ├── collections ├── calculations │ ├── Collections_AveragingDouble.java │ ├── Collections_GroupingBy.java │ ├── Collections_Joining.java │ ├── Collections_MaxMinCount.java │ └── Collections_PartitioningBy.java ├── datasearch │ ├── DataSearch_FindFirstAny.java │ └── DataSearch_Match.java ├── diamond │ └── Collections_Diamond.java ├── improvements │ ├── Collections_ComputeIfAbsent.java │ ├── Collections_ComputeIfPresent.java │ ├── Collections_RemoveIf.java │ └── Collections_ReplaceAll.java ├── lambda │ ├── CollectionsLambda_Combined.java │ ├── CollectionsLambda_Filter.java │ ├── CollectionsLambda_ForEach.java │ └── CollectionsLambda_Sort.java └── mergemap │ ├── Collections_FlatMap.java │ ├── Collections_Map.java │ └── Collections_Merge.java ├── concurrency ├── concurrentpackage │ ├── Concurrency_CollectionsSyncronized.java │ ├── Concurrency_CollectionsSyncronizedForEach.java │ ├── Concurrency_CopyOnWriteArrayList.java │ ├── Concurrency_CyclicBarrier.java │ ├── Concurrency_LinkedBlockingDeque.java │ └── Concurrency_LinkedBlockingQueue.java ├── executetasks │ ├── Schedule_SingleThread.java │ ├── Schedule_SingleThreadCallable.java │ ├── Schedule_SingleThreadFixedDelay.java │ ├── Schedule_SingleThreadFixedRate.java │ ├── TasksMulti_CachedThreadPool.java │ ├── TasksMulti_FixedThreadPool.java │ ├── TasksMulti_ScheduledThreadPool.java │ ├── Tasks_RunnableCallable.java │ ├── Tasks_ShutdownNow.java │ ├── Tasks_SingleThread.java │ ├── Tasks_SingleThreadAwaitTermination.java │ ├── Tasks_SingleThreadCallable.java │ ├── Tasks_SingleThreadFuture.java │ ├── Tasks_SingleThreadInvokeAll.java │ ├── Tasks_SingleThreadInvokeAny.java │ ├── Tasks_SingleThreadManyTasks.java │ └── Tasks_SingleThreadSubmit.java ├── forkjoin │ ├── ForkJoin_RecursiveAction.java │ └── ForkJoin_RecursiveTask.java └── locks │ ├── Locks_Fair.java │ ├── Locks_LockTwice.java │ ├── Locks_ReadWriteLock.java │ ├── Locks_ReadWriteLockInverted.java │ ├── Locks_ReentrantLock.java │ ├── Locks_TryLock.java │ ├── Locks_TryLockMultithread.java │ ├── Locks_TryLockTimeout.java │ └── Locks_UnlockWithoutLock.java ├── fileio ├── fileimprovements │ ├── Improvements_Find.java │ ├── Improvements_Lines.java │ ├── Improvements_List.java │ ├── Improvements_Walk.java │ └── Improvements_WalkDepth.java ├── files │ ├── Files_BasicFileAttributeView.java │ ├── Files_BasicFileAttributes.java │ ├── Files_Checks.java │ ├── Files_CopyFromPath.java │ ├── Files_CopyPath.java │ ├── Files_CopyToPath.java │ ├── Files_CreateDirectories.java │ ├── Files_CreateDirectory.java │ ├── Files_CreateFile.java │ ├── Files_DeletePath.java │ ├── Files_LastModified.java │ ├── Files_MoveFile.java │ ├── Files_Owner.java │ ├── Files_ReadAllLines.java │ ├── Files_SameFile.java │ └── Files_WriteFile.java ├── paths │ ├── Paths_Creation.java │ ├── Paths_CreationDoesntExists.java │ ├── Paths_Information.java │ ├── Paths_Names.java │ ├── Paths_Normalize.java │ ├── Paths_Relativize.java │ ├── Paths_Resolve.java │ ├── Paths_SubPath.java │ ├── Paths_ToAbsolute.java │ ├── Paths_ToFile.java │ └── Paths_ToRealPath.java ├── recursiveaccess │ ├── Recursive_DirectoryStream.java │ ├── Recursive_FileVisitor.java │ ├── Recursive_SimpleFileVisitor.java │ ├── Recursive_VisitorDirectory.java │ ├── Recursive_VisitorIgnoreSiblings.java │ ├── Recursive_VisitorOptionsAndDepth.java │ └── Recursive_VisitorTerminate.java └── watchservice │ ├── WatchService_CreateDelete.java │ ├── WatchService_File.java │ ├── WatchService_Modify.java │ └── WatchService_Poll.java ├── lambda ├── builtininterfaces │ ├── BuiltInInterfaces_ConsumerExample.java │ ├── BuiltInInterfaces_ConsumerPrimitive.java │ ├── BuiltInInterfaces_FunctionExample.java │ ├── BuiltInInterfaces_FunctionPrimitive.java │ ├── BuiltInInterfaces_OperatorExample.java │ ├── BuiltInInterfaces_OperatorPrimitive.java │ ├── BuiltInInterfaces_OptionalCreation.java │ ├── BuiltInInterfaces_OptionalGetEmpty.java │ ├── BuiltInInterfaces_OptionalIfPresent.java │ ├── BuiltInInterfaces_OptionalNullable.java │ ├── BuiltInInterfaces_OptionalOrElse.java │ ├── BuiltInInterfaces_OptionalOrElseThrow.java │ ├── BuiltInInterfaces_OptionalPrimitive.java │ ├── BuiltInInterfaces_PredicateExample.java │ ├── BuiltInInterfaces_PredicatePrimitive.java │ ├── BuiltInInterfaces_SupplierExample.java │ ├── BuiltInInterfaces_SupplierPrimitive.java │ └── BuiltInInterfaces_SupplierUseCase.java ├── functionalinterfaces │ ├── FunctionalInterfaces_Basic.java │ ├── FunctionalInterfaces_ClassCompilationError.java │ ├── FunctionalInterfaces_DefaultStatic.java │ ├── FunctionalInterfaces_Extends.java │ ├── FunctionalInterfaces_ExtendsNewMethod.java │ ├── FunctionalInterfaces_Implement.java │ ├── FunctionalInterfaces_InterfaceCompilationError.java │ ├── FunctionalInterfaces_OverrideObject.java │ └── FunctionalInterfaces_ReturnType.java ├── lambdaexpression │ ├── LambdaExpression_AccessExternalVar.java │ ├── LambdaExpression_Ambiguity.java │ ├── LambdaExpression_AnonymousClass.java │ ├── LambdaExpression_Block.java │ ├── LambdaExpression_ForEach.java │ ├── LambdaExpression_FunctionalInterface.java │ ├── LambdaExpression_Parenthesis.java │ ├── LambdaExpression_Shadowing.java │ ├── LambdaExpression_SimpleComplete.java │ ├── LambdaExpression_TypeInference.java │ └── LambdaExpression_VarType.java └── methodreference │ ├── MethodReference_Complex.java │ ├── MethodReference_Constructor.java │ ├── MethodReference_CustomType.java │ ├── MethodReference_Instance.java │ ├── MethodReference_Static.java │ ├── MethodReference_Type.java │ ├── MethodReference_TypeWithParam.java │ └── MethodReference_Variaty.java ├── languageenhancements ├── literals │ ├── Literals_Complete.java │ ├── Literals_Prefix.java │ ├── Literals_Suffix.java │ └── Literals_Underscore.java ├── multipleexception │ ├── MultipleException_CheckedException.java │ ├── MultipleException_Complete.java │ ├── MultipleException_GenericsLower.java │ ├── MultipleException_MultipleSameCatch.java │ ├── MultipleException_OverrideVar.java │ ├── MultipleException_Redundant.java │ └── MultipleException_RepeatException.java ├── staticdefaultininterfaces │ ├── StaticDefaultInInterfaces_Abstract.java │ ├── StaticDefaultInInterfaces_AccessModifiers.java │ ├── StaticDefaultInInterfaces_Complete.java │ ├── StaticDefaultInInterfaces_Default.java │ ├── StaticDefaultInInterfaces_InterfaceInheritance.java │ ├── StaticDefaultInInterfaces_RepeatedDefault.java │ ├── StaticDefaultInInterfaces_RepeatedDefaultSuper.java │ └── StaticDefaultInInterfaces_Static.java ├── stringinswitch │ ├── StringInSwitch_Break.java │ ├── StringInSwitch_Complete.java │ ├── StringInSwitch_ConstantOnly.java │ ├── StringInSwitch_Default.java │ ├── StringInSwitch_Empty.java │ └── StringInSwitch_Type.java └── trywithresources │ ├── TryWithResouces_AutoCloseable.java │ ├── TryWithResouces_CloseException.java │ ├── TryWithResouces_CommonTry.java │ ├── TryWithResouces_Complete.java │ ├── TryWithResouces_Java6.java │ ├── TryWithResouces_NoAutoCloseable.java │ ├── TryWithResouces_Order.java │ ├── TryWithResouces_ResourceInsideTry.java │ ├── TryWithResouces_Suppressed.java │ └── TryWithResouces_WithCatchFinally.java ├── localization ├── datetime │ ├── duration │ │ ├── Duration_Between.java │ │ ├── Duration_BiggerValues.java │ │ ├── Duration_Compatibility.java │ │ ├── Duration_LocalDate.java │ │ └── Duration_Of.java │ ├── instant │ │ ├── Instant_Constructor.java │ │ ├── Instant_Convert.java │ │ ├── Instant_Immutability.java │ │ ├── Instant_Manipulate.java │ │ ├── Instant_Now.java │ │ └── Instant_Of.java │ ├── localdate │ │ ├── LocalDate_AdjustDifferentUnit.java │ │ ├── LocalDate_Chaining.java │ │ ├── LocalDate_Constructor.java │ │ ├── LocalDate_Immutability.java │ │ ├── LocalDate_Invalid.java │ │ ├── LocalDate_Manipulate.java │ │ ├── LocalDate_Now.java │ │ └── LocalDate_Of.java │ ├── localdatetime │ │ ├── LocalDateTime_AdjustDifferentUnit.java │ │ ├── LocalDateTime_Chaining.java │ │ ├── LocalDateTime_Constructor.java │ │ ├── LocalDateTime_Immutability.java │ │ ├── LocalDateTime_Invalid.java │ │ ├── LocalDateTime_Manipulate.java │ │ ├── LocalDateTime_Now.java │ │ └── LocalDateTime_Of.java │ ├── localtime │ │ ├── LocalTime_AdjustDifferentUnit.java │ │ ├── LocalTime_Chaining.java │ │ ├── LocalTime_Constructor.java │ │ ├── LocalTime_Immutability.java │ │ ├── LocalTime_Invalid.java │ │ ├── LocalTime_Manipulate.java │ │ ├── LocalTime_Now.java │ │ └── LocalTime_Of.java │ └── period │ │ ├── Period_Between.java │ │ ├── Period_BiggerValues.java │ │ ├── Period_Compatibility.java │ │ ├── Period_Curiosities.java │ │ ├── Period_Instant.java │ │ ├── Period_LocalTime.java │ │ └── Period_Of.java ├── formats │ ├── dateformat │ │ ├── DateFormat_Instance.java │ │ └── DateFormat_Parse.java │ ├── datetimeformatter │ │ ├── DateTimeFormatter_Custom.java │ │ ├── DateTimeFormatter_Error.java │ │ ├── DateTimeFormatter_ErrorCustom.java │ │ ├── DateTimeFormatter_FormatStyle.java │ │ ├── DateTimeFormatter_Inverted.java │ │ ├── DateTimeFormatter_Locale.java │ │ ├── DateTimeFormatter_Parse.java │ │ └── DateTimeFormatter_Predefined.java │ ├── decimalformat │ │ ├── DecimalFormat_Instance.java │ │ ├── DecimalFormat_Locale.java │ │ └── DecimalFormat_Strings.java │ ├── numberformat │ │ ├── NumberFormat_Currency.java │ │ ├── NumberFormat_Instance.java │ │ ├── NumberFormat_NumberToString.java │ │ ├── NumberFormat_Percent.java │ │ ├── NumberFormat_Percent2.java │ │ └── NumberFormat_StringToNumber.java │ └── simpledateformat │ │ ├── SimpleDateFormat_Instance.java │ │ └── SimpleDateFormat_Parse.java ├── locale │ ├── Locale_Complete.java │ ├── Locale_LocaleAvailable.java │ ├── Locale_LocaleCase.java │ ├── Locale_LocaleCommons.java │ ├── Locale_LocaleDefault.java │ ├── Locale_LocaleInstantiation.java │ ├── Locale_LocaleLanguageCountry.java │ ├── Locale_LocaleLanguageOnly.java │ └── Locale_VarScriptExtension.java ├── resourcebundle │ ├── ResourceBundle_Complete.java │ ├── ResourceBundle_Inheritance.java │ ├── ResourceBundle_JavaBundle.java │ ├── ResourceBundle_JavaClassTakesPrecedence.java │ ├── ResourceBundle_KeysProgrammatically.java │ └── ResourceBundle_NotExactLocale.java └── timezones │ ├── ZonedDateTime_Chaining.java │ ├── ZonedDateTime_Constructor.java │ ├── ZonedDateTime_DaylightSavings.java │ ├── ZonedDateTime_Immutability.java │ ├── ZonedDateTime_Invalid.java │ ├── ZonedDateTime_Manipulate.java │ ├── ZonedDateTime_Now.java │ ├── ZonedDateTime_Of.java │ └── ZonedDateTime_Zones.java └── streams ├── parallelstreams ├── Streams_Parallel.java ├── Streams_ParallelFindAny.java ├── Streams_ParallelForEach.java ├── Streams_ParallelForEachOrdered.java ├── Streams_ParallelGroupingByConcurrent.java ├── Streams_ParallelPerformance.java ├── Streams_ParallelReduceAssociative.java ├── Streams_ParallelReduceNonAssociative.java ├── Streams_ParallelStatefulOperation.java ├── Streams_ParallelStream.java └── Streams_ParallelToConcurrentMap.java └── usingstreams ├── Streams_ArraysStream.java ├── Streams_ChangeBackingList.java ├── Streams_Distinct.java ├── Streams_Filter.java ├── Streams_FindFirstAny.java ├── Streams_FlatMap.java ├── Streams_IntRangeStream.java ├── Streams_LazyMap.java ├── Streams_LazyNoFinal.java ├── Streams_Limit.java ├── Streams_ListStream.java ├── Streams_Map.java ├── Streams_Match.java ├── Streams_MaxMinCount.java ├── Streams_Of.java ├── Streams_Optional.java ├── Streams_Peek.java ├── Streams_Pipeline.java ├── Streams_ReuseStream.java ├── Streams_Skip.java ├── Streams_Sorted.java ├── collect ├── Streams_CollectorAveragingInt.java ├── Streams_CollectorGroupingBy.java ├── Streams_CollectorGroupingByDownstream.java ├── Streams_CollectorGroupingByMapFactory.java ├── Streams_CollectorJoining.java ├── Streams_CollectorMapping.java ├── Streams_CollectorPartitioningBy.java ├── Streams_CollectorPartitioningByDownstream.java ├── Streams_CollectorToCollect.java ├── Streams_CollectorToMap.java └── Streams_CollectorToMapDuplicateKey.java ├── primitives ├── Streams_Generate.java ├── Streams_MapTo.java ├── Streams_Primitives.java ├── Streams_RangeClosed.java └── Streams_Statistics.java └── reduce ├── Streams_Reduce.java ├── Streams_ReduceCombiner.java └── Streams_ReduceIdentity.java /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.png binary 3 | *.jpg binary 4 | *.sh text eol=lf 5 | *.bat text eol=crlf 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | book-output 2 | book-release* 3 | 4 | ### NODE.JS ### 5 | node_modules* 6 | npm-debug.log 7 | 8 | ### OSX ### 9 | *.DS_Store 10 | ._* 11 | 12 | ### Nosso exemplos ### 13 | arquivo*.txt 14 | 15 | ### Eclipse ### 16 | .settings/ 17 | .project 18 | .classpath 19 | build 20 | bin 21 | 22 | ### IDEA ### 23 | .idea/* 24 | *.iml 25 | out 26 | 27 | # warn IDEA to ignore all files that won't be compiling due to educational examples 28 | !.idea/compiler.xml 29 | 30 | # ignores local travis config folder 31 | .travis 32 | 33 | ### others ### 34 | .vscode 35 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@semantic-release/commit-analyzer", 4 | "@semantic-release/release-notes-generator", 5 | "@semantic-release/changelog", 6 | ["@semantic-release/git", { 7 | "assets": ["package.json", "CHANGELOG.md"], 8 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" 9 | }], 10 | "@semantic-release/github" 11 | ] 12 | } -------------------------------------------------------------------------------- /C-references.asc: -------------------------------------------------------------------------------- 1 | [[C-references]] 2 | [appendix] 3 | == Referências 4 | 5 | include::README.asc[lines=34..-1] 6 | -------------------------------------------------------------------------------- /LICENSE.asc: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Rinaldo Pitzer Jr. e Rodrigo Moutinho 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /book/01-getting-started/sections/01-introduction.asc: -------------------------------------------------------------------------------- 1 | === Introdução 2 | 3 | include::../../../README.asc[lines=5..6] 4 | -------------------------------------------------------------------------------- /book/01-getting-started/sections/02-objectives.asc: -------------------------------------------------------------------------------- 1 | === Objetivos 2 | 3 | Como guia para criação deste livro foi utilizado todos os objetivos citados na seção _"Review Exam Topics"_, de acordo com o https://education.oracle.com/upgrade-to-java-se-8-ocp/pexam_1Z0-813[site da certificação]. 4 | 5 | A missão deste livro é criar o maior número de exemplos práticos possíveis para ajudar você a colocar a mão na massa. Quanto maior for seu contato com os códigos da versão 8 do Java, mais confiante estará na hora do exame, e também para lidar com projetos em Java 8 no mercado de trabalho. 6 | -------------------------------------------------------------------------------- /book/contributors.asc: -------------------------------------------------------------------------------- 1 | [preface] 2 | == Contribuidores 3 | 4 | Por ser um livro de código aberto, recebemos várias mudanças de conteúdo e erratas ao longo de seu desenvolvimento. Aqui estão todas as pessoas que contribuíram para a versão em português do livro como um projeto de código aberto. Obrigado a todos por ajudarem a tornar este livro melhor para todos. 5 | 6 | [source,tabsize=8] 7 | ---- 8 | include::contributors.txt[] 9 | ---- 10 | 11 | Esse texto é praticamente o mesmo utilizado no *Pro Git 2*. Acesse o texto original https://raw.githubusercontent.com/progit/progit2/master/book/contributors.asc[aqui]. 12 | -------------------------------------------------------------------------------- /book/license.asc: -------------------------------------------------------------------------------- 1 | [preface] 2 | == Licença 3 | 4 | include::../LICENSE.asc[] 5 | -------------------------------------------------------------------------------- /ch01-getting-started.asc: -------------------------------------------------------------------------------- 1 | [[ch01-getting-started]] 2 | == Começando 3 | 4 | include::book/01-getting-started/sections/01-introduction.asc[] 5 | include::book/01-getting-started/sections/02-objectives.asc[] 6 | -------------------------------------------------------------------------------- /ch02-language-enhancement.asc: -------------------------------------------------------------------------------- 1 | [[ch02-language-enhancement]] 2 | == Language Enhancements 3 | 4 | include::book/02-language-enhancement/sections/01-string-in-switch-and-literals.asc[] 5 | include::book/02-language-enhancement/sections/02-try-with-resources.asc[] 6 | include::book/02-language-enhancement/sections/03-multiple-exception.asc[] 7 | include::book/02-language-enhancement/sections/04-static-default-in-interfaces.asc[] 8 | -------------------------------------------------------------------------------- /ch03-localization.asc: -------------------------------------------------------------------------------- 1 | [[ch03-localization]] 2 | == Localization 3 | 4 | include::book/03-localization/sections/01-locale.asc[] 5 | include::book/03-localization/sections/02-resource-bundle.asc[] 6 | include::book/03-localization/sections/03-date-time.asc[] 7 | include::book/03-localization/sections/04-formats.asc[] 8 | include::book/03-localization/sections/05-time-zones.asc[] 9 | -------------------------------------------------------------------------------- /ch04-lambda.asc: -------------------------------------------------------------------------------- 1 | [[ch04-lambda]] 2 | == Lambda 3 | 4 | include::book/04-lambda/sections/01-functional-interfaces.asc[] 5 | include::book/04-lambda/sections/02-lambda-expression.asc[] 6 | include::book/04-lambda/sections/03-built-in-interfaces.asc[] 7 | include::book/04-lambda/sections/04-method-reference.asc[] -------------------------------------------------------------------------------- /ch05-java-streams.asc: -------------------------------------------------------------------------------- 1 | [[ch05-java-streams]] 2 | == Java Streams 3 | 4 | include::book/05-java-streams/sections/01-using-streams.asc[] 5 | include::book/05-java-streams/sections/02-parallel-streams.asc[] -------------------------------------------------------------------------------- /ch06-concurrency.asc: -------------------------------------------------------------------------------- 1 | [[ch06-concurrency]] 2 | == Concurrency 3 | 4 | include::book/06-concurrency/sections/01-concurrent-package.asc[] 5 | include::book/06-concurrency/sections/02-locks.asc[] 6 | include::book/06-concurrency/sections/03-execute-tasks.asc[] 7 | include::book/06-concurrency/sections/04-fork-join.asc[] 8 | -------------------------------------------------------------------------------- /ch07-java-file-io.asc: -------------------------------------------------------------------------------- 1 | [[ch07-java-file-io]] 2 | == Java File I/O (NIO.2) 3 | 4 | include::book/07-file-io/sections/01-paths.asc[] 5 | include::book/07-file-io/sections/02-files.asc[] 6 | include::book/07-file-io/sections/03-recursive-access.asc[] 7 | include::book/07-file-io/sections/04-file-improvements.asc[] 8 | include::book/07-file-io/sections/05-watch-service.asc[] -------------------------------------------------------------------------------- /ch08-java-collections.asc: -------------------------------------------------------------------------------- 1 | [[ch08-java-collections]] 2 | == Java Collections 3 | 4 | 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__. 5 | 6 | include::book/08-java-collections/sections/01-diamond.asc[] 7 | include::book/08-java-collections/sections/02-collections-lambda.asc[] 8 | include::book/08-java-collections/sections/03-data-search.asc[] 9 | include::book/08-java-collections/sections/04-calculations.asc[] 10 | include::book/08-java-collections/sections/05-collection-improvements.asc[] 11 | include::book/08-java-collections/sections/06-merge-map.asc[] -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | ebook: 5 | image: asciidoctor/docker-asciidoctor:1.1.0 6 | volumes: 7 | - .:/documents/ 8 | entrypoint: scripts/docker-startup.sh 9 | network_mode: bridge 10 | 11 | travis: 12 | build: 13 | context: . 14 | dockerfile: ./docker/travis/Dockerfile 15 | volumes: 16 | - .:/app 17 | - ./.travis:/root/.travis 18 | network_mode: bridge 19 | -------------------------------------------------------------------------------- /docker/travis/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:alpine 2 | 3 | RUN apk --update add build-base git \ 4 | && gem install travis \ 5 | && apk del build-base \ 6 | && rm -rf /var/cache/apk/* \ 7 | && rm -rf /tmp/* \ 8 | && mkdir app 9 | 10 | WORKDIR app 11 | VOLUME ["/app"] 12 | 13 | LABEL maintainer="twitter.com/rcmoutinho" 14 | LABEL description="Travis CLI in a docker container" 15 | 16 | ENTRYPOINT ["travis"] 17 | CMD ["--help"] 18 | -------------------------------------------------------------------------------- /images/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duke-certification/java6-to-java8/b6e93159a9e84c03f547c9c90fc8734f56ae816a/images/cover.png -------------------------------------------------------------------------------- /images/ebook-400x400.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duke-certification/java6-to-java8/b6e93159a9e84c03f547c9c90fc8734f56ae816a/images/ebook-400x400.png -------------------------------------------------------------------------------- /java6-to-java8.asc: -------------------------------------------------------------------------------- 1 | = Guia Prático para Certificação: Atualize sua certificação Java 6 para Java 8 2 | Rinaldo Pitzer Jr.; Rodrigo Moutinho 3 | :doctype: book 4 | :docinfo: 5 | :toc: 6 | :toclevels: 2 7 | :pagenums: 8 | :front-cover-image: image:images/cover.png[width=1050,height=1600] 9 | :icons: font 10 | :source-highlighter: rouge 11 | 12 | :appendix-caption: Apêndice 13 | :toc-title: Índice 14 | 15 | ifdef::ebook-format[:leveloffset: -1] 16 | 17 | include::book/license.asc[] 18 | 19 | include::book/contributors.asc[] 20 | 21 | include::ch01-getting-started.asc[] 22 | 23 | include::ch02-language-enhancement.asc[] 24 | 25 | include::ch03-localization.asc[] 26 | 27 | include::ch04-lambda.asc[] 28 | 29 | include::ch05-java-streams.asc[] 30 | 31 | include::ch06-concurrency.asc[] 32 | 33 | include::ch07-java-file-io.asc[] 34 | 35 | include::ch08-java-collections.asc[] 36 | 37 | include::ch09-assume.asc[] 38 | 39 | include::A-tricks-to-succeed.asc[] 40 | 41 | include::B-test-yourself.asc[] 42 | 43 | include::C-references.asc[] 44 | -------------------------------------------------------------------------------- /resources/Text.properties: -------------------------------------------------------------------------------- 1 | phone=phone 2 | tripod tripod 3 | pen:pen 4 | keyboard=keyboard 5 | glass=glass 6 | sticker sticker 7 | paper:paper 8 | rubber rubber -------------------------------------------------------------------------------- /resources/Text_es.properties: -------------------------------------------------------------------------------- 1 | keyboard=tec\ 2 | lado -------------------------------------------------------------------------------- /resources/Text_es_ES.properties: -------------------------------------------------------------------------------- 1 | !arquivo do locale es_ES 2 | glass=\tvaso -------------------------------------------------------------------------------- /resources/Text_fr_CA.java: -------------------------------------------------------------------------------- 1 | import java.util.ListResourceBundle; 2 | 3 | public class Text_fr_CA extends ListResourceBundle { 4 | 5 | @Override 6 | protected Object[][] getContents() { 7 | return new Object[][] { 8 | {"pen", "stylo"}, 9 | {"glass", "verre"}, 10 | {"keyboard", "clavier"} 11 | }; 12 | } 13 | } -------------------------------------------------------------------------------- /resources/Text_fr_CA.properties: -------------------------------------------------------------------------------- 1 | pen=stylo-in-ignored-properties 2 | glass=stylo-in-ignored-properties 3 | keyboard=stylo-in-ignored-properties -------------------------------------------------------------------------------- /resources/Text_fr_FR.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.ListResourceBundle; 3 | 4 | public class Text_fr_FR extends ListResourceBundle { 5 | 6 | @Override 7 | protected Object[][] getContents() { 8 | return new Object[][] { 9 | {"ten", new BigDecimal("10")} 10 | }; 11 | } 12 | } -------------------------------------------------------------------------------- /resources/Text_it.properties: -------------------------------------------------------------------------------- 1 | keyboard=tastiera -------------------------------------------------------------------------------- /resources/Text_pt.properties: -------------------------------------------------------------------------------- 1 | paper = papel -------------------------------------------------------------------------------- /resources/Text_pt_BR.properties: -------------------------------------------------------------------------------- 1 | #arquivo do locale pt_BR 2 | pen=caneta -------------------------------------------------------------------------------- /src/org/j6toj8/collections/calculations/Collections_AveragingDouble.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.calculations; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class Collections_AveragingDouble { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 12 | 13 | Double media = list.stream() 14 | .collect(Collectors.averagingDouble(n -> n.doubleValue())); 15 | 16 | System.out.println("Média: " + media); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/calculations/Collections_GroupingBy.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.calculations; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | 8 | public class Collections_GroupingBy { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 13 | 14 | Map> mapaDivisaoPor3 = list.stream() 15 | .collect(Collectors.groupingBy(n -> n % 3)); 16 | 17 | System.out.println("Mapa de resto da divisão por 3: " + mapaDivisaoPor3); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/calculations/Collections_Joining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.calculations; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class Collections_Joining { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 12 | 13 | String juncao = list.stream() 14 | .map(n -> n.toString()) 15 | .collect(Collectors.joining()); 16 | 17 | System.out.println("Junção dos valores como String: " + juncao); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/calculations/Collections_MaxMinCount.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.calculations; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.OptionalInt; 6 | 7 | public class Collections_MaxMinCount { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 12 | 13 | OptionalInt max = list.stream() 14 | .mapToInt(Integer::intValue) // transforma para int 15 | .max(); 16 | System.out.println("Max: " + max.getAsInt()); 17 | 18 | OptionalInt min = list.stream() 19 | .mapToInt(Integer::intValue) // transforma para int 20 | .min(); 21 | System.out.println("Min: " + min.getAsInt()); 22 | 23 | long count = list.stream() 24 | .mapToInt(Integer::intValue) // transforma para int 25 | .count(); 26 | System.out.println("Count: " + count); 27 | // end::code[] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/calculations/Collections_PartitioningBy.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.calculations; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | 8 | public class Collections_PartitioningBy { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 13 | 14 | Map> mapaParImpar = list.stream() 15 | .collect(Collectors.partitioningBy(n -> n % 2 == 0)); 16 | 17 | System.out.println("Mapa de pares e ímpares: " + mapaParImpar); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/datasearch/DataSearch_FindFirstAny.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.datasearch; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class DataSearch_FindFirstAny { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 2, 9, 54, 13, 87, 23, 97, 34, 17, 34); 11 | 12 | list.parallelStream() 13 | .findFirst() 14 | .ifPresent(n -> System.out.println("First: " + n)); 15 | 16 | list.parallelStream() 17 | .findAny() 18 | .ifPresent(n -> System.out.println("Any: " + n)); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/datasearch/DataSearch_Match.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.datasearch; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class DataSearch_Match { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 2, 9, 54, 13, 87, 23, 97, 34, 17, 34); 11 | 12 | boolean anyMatch = list.stream().anyMatch(n -> n > 50); 13 | System.out.println("anyMatch: " + anyMatch); 14 | 15 | boolean allMatch = list.stream().allMatch(n -> n > 50); 16 | System.out.println("allMatch: " + allMatch); 17 | 18 | boolean noneMatch = list.stream().noneMatch(n -> n > 50); 19 | System.out.println("noneMatch: " + noneMatch); 20 | // end::code[] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/improvements/Collections_ComputeIfAbsent.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.improvements; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Collections_ComputeIfAbsent { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | HashMap map = new HashMap(); 10 | map.put("A", "A".hashCode()); 11 | map.put("B", "B".hashCode()); 12 | 13 | System.out.println("Map antes do computeIfAbsent: " + map); 14 | map.computeIfAbsent("A", k -> k.hashCode()); 15 | map.computeIfAbsent("C", k -> k.hashCode()); 16 | System.out.println("Map depois do computeIfAbsent: " + map); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/improvements/Collections_ComputeIfPresent.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.improvements; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Collections_ComputeIfPresent { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | HashMap map = new HashMap(); 10 | map.put("A", "A".hashCode()); 11 | map.put("B", "B".hashCode()); 12 | 13 | System.out.println("Map antes do computeIfPresent: " + map); 14 | // k = chave; v = valor 15 | map.computeIfPresent("A", (k, v) -> k.hashCode() * v); 16 | map.computeIfPresent("B", (k, v) -> k.hashCode() * v); 17 | map.computeIfPresent("C", (k, v) -> k.hashCode() * v); 18 | System.out.println("Map depois do computeIfPresent: " + map); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/improvements/Collections_RemoveIf.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.improvements; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Collections_RemoveIf { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | List list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9)); 12 | 13 | System.out.println("Lista antes do removeIf: " + list); 14 | list.removeIf(n -> n % 2 == 0); // remove números pares 15 | System.out.println("Lista depois do removeIf: " + list); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/improvements/Collections_ReplaceAll.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.improvements; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class Collections_ReplaceAll { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | List list = new ArrayList(Arrays.asList(1,2,3,4,5,6,7,8,9)); 12 | 13 | System.out.println("Lista antes do replaceAll: " + list); 14 | list.replaceAll(n -> n * 2); // multiplica todos os elementos por 2 15 | System.out.println("Lista depois do replaceAll: " + list); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/lambda/CollectionsLambda_Combined.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CollectionsLambda_Combined { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 7, 2, 9, 54, 13, 87, 23, 97, 34, 17, 34, 89, 35, 26); 11 | list.stream() 12 | .sorted() 13 | .filter(n -> n > 10) 14 | .filter(n -> n % 2 == 0) 15 | .forEach(System.out::println); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/lambda/CollectionsLambda_Filter.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CollectionsLambda_Filter { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 7, 2, 9); 11 | list.stream() 12 | .filter(n -> n > 2) 13 | .forEach(System.out::println); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/lambda/CollectionsLambda_ForEach.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CollectionsLambda_ForEach { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 7, 2, 9); 11 | list.forEach(System.out::println); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/lambda/CollectionsLambda_Sort.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CollectionsLambda_Sort { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 6, 7, 2, 9); 11 | list.stream() 12 | .sorted() 13 | .forEach(System.out::println); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/mergemap/Collections_FlatMap.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.mergemap; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Collections_FlatMap { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList("Manoel"); 11 | 12 | System.out.println("\n Com map: "); 13 | // com map - as letras da String viram 14 | // um Stream dentro de outro Stream 15 | list.stream() 16 | .map(s -> Arrays.stream(s.split(""))) 17 | .forEach(System.out::println); 18 | 19 | System.out.println("\n Com flatMap: "); 20 | // com flatMap - as letras da String viram dados 21 | // do próprio Stream 22 | list.stream() 23 | .flatMap(s -> Arrays.stream(s.split(""))) 24 | .forEach(System.out::println); 25 | // end::code[] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/mergemap/Collections_Map.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.mergemap; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Collections_Map { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1,2,3,4,5,6,7,8,9); 11 | 12 | list.stream() 13 | .map(e -> e * 2) 14 | .forEach(System.out::println); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/collections/mergemap/Collections_Merge.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.collections.mergemap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Collections_Merge { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | HashMap map = new HashMap(); 10 | map.put(1, "String1-"); 11 | map.put(2, "String2-"); 12 | 13 | System.out.println("Map antes do merge: " + map); 14 | map.merge(1, "StringA", (v1, v2) -> v1.concat(v2)); 15 | map.merge(2, "StringB", (v1, v2) -> v1.concat(v2)); 16 | map.merge(3, "StringC", (v1, v2) -> v1.concat(v2)); 17 | map.merge(4, "StringD", (v1, v2) -> v1.concat(v2)); 18 | System.out.println("Map depois do merge: " + map); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.concurrentpackage; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | public class Concurrency_CollectionsSyncronized { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | // Concurrent Map, garante o acesso de múltiplas threads 13 | Map concurrentHashMap = new ConcurrentHashMap<>(); 14 | 15 | // Map Comum, NÃO garante o acesso de múltiplas threads 16 | Map map = new HashMap<>(); 17 | 18 | // Syncronized Map, garante o acesso de múltiplas threads 19 | Map synchronizedMap = Collections.synchronizedMap(map); 20 | // end::code[] 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.concurrentpackage; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | 8 | public class Concurrency_CollectionsSyncronizedForEach { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | Map map = new HashMap(); 13 | map.put(1, "A"); 14 | map.put(2, "B"); 15 | map.put(3, "C"); 16 | Map synchronizedMap = Collections.synchronizedMap(map); 17 | 18 | for (Entry entry : synchronizedMap.entrySet()) { 19 | synchronizedMap.remove(1); 20 | } 21 | // end::code[] 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.concurrentpackage; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CopyOnWriteArrayList; 5 | 6 | public class Concurrency_CopyOnWriteArrayList { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = new CopyOnWriteArrayList(); 11 | list.add("A"); 12 | list.add("B"); 13 | list.add("C"); 14 | 15 | for (String string : list) { 16 | System.out.println(string); 17 | if (string.equals("A")) { 18 | list.add("D"); 19 | } 20 | } 21 | 22 | System.out.println("Lista final: " + list); 23 | // end::code[] 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.concurrentpackage; 2 | 3 | import java.util.concurrent.BlockingDeque; 4 | import java.util.concurrent.LinkedBlockingDeque; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class Concurrency_LinkedBlockingDeque { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | BlockingDeque queue = new LinkedBlockingDeque(); 12 | 13 | try { 14 | queue.offerFirst("ABC", 1, TimeUnit.SECONDS); 15 | queue.offerLast("DEF", 1, TimeUnit.SECONDS); 16 | } catch (InterruptedException e) { 17 | System.out.println("Não conseguiu inserir em menos de 1 segundo."); 18 | } 19 | 20 | try { 21 | queue.pollFirst(1, TimeUnit.SECONDS); 22 | queue.pollLast(1, TimeUnit.SECONDS); 23 | } catch (InterruptedException e) { 24 | System.out.println("Não conseguiu remover em menos de 1 segundo."); 25 | } 26 | // end::code[] 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.concurrentpackage; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.LinkedBlockingQueue; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class Concurrency_LinkedBlockingQueue { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | BlockingQueue queue = new LinkedBlockingQueue(); 12 | 13 | try { 14 | queue.offer("ABC", 1, TimeUnit.SECONDS); 15 | } catch (InterruptedException e) { 16 | System.out.println("Não conseguiu inserir em menos de 1 segundo."); 17 | } 18 | 19 | try { 20 | queue.poll(1, TimeUnit.SECONDS); 21 | } catch (InterruptedException e) { 22 | System.out.println("Não conseguiu remover em menos de 1 segundo."); 23 | } 24 | // end::code[] 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Schedule_SingleThread.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.time.LocalTime; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ScheduledExecutorService; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class Schedule_SingleThread { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | ScheduledExecutorService executor = null; 13 | try { 14 | executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread 15 | System.out.println("Agora: " + LocalTime.now()); // imprime a hora atual 16 | 17 | executor.schedule(() -> System.out.println("Execução: " + LocalTime.now()), 3, TimeUnit.SECONDS); 18 | } finally { 19 | if (executor != null) { 20 | executor.shutdown(); 21 | } 22 | } 23 | // end::code[] 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_ShutdownNow.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class Tasks_ShutdownNow { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ExecutorService executor = null; 11 | try { 12 | executor = Executors.newSingleThreadExecutor(); 13 | executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); 14 | System.out.println("Thread Principal: " + Thread.currentThread().getName()); 15 | } finally { 16 | if (executor != null) { 17 | executor.shutdownNow(); // TENTA encerrar todas as threads imediatamente 18 | } 19 | } 20 | // end::code[] 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_SingleThread.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class Tasks_SingleThread { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ExecutorService executor = null; 11 | try { 12 | executor = Executors.newSingleThreadExecutor(); // executor com uma única thread 13 | executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); 14 | System.out.println("Thread Principal: " + Thread.currentThread().getName()); 15 | } finally { 16 | if (executor != null) { 17 | executor.shutdown(); 18 | } 19 | } 20 | // end::code[] 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadCallable.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Future; 7 | 8 | public class Tasks_SingleThreadCallable { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | ExecutorService executor = null; 13 | try { 14 | executor = Executors.newSingleThreadExecutor(); 15 | Future retornoDaTarefa = executor.submit(() -> "String que será retornada"); 16 | 17 | // O .get() abaixo irá esperar a tarefa finalizar para pegar seu retorno 18 | System.out.println("Retorno da tarefa: " + retornoDaTarefa.get()); 19 | } catch (InterruptedException | ExecutionException e) { 20 | System.out.println("Execução interrompida."); 21 | } finally { 22 | if (executor != null) { 23 | executor.shutdown(); 24 | } 25 | } 26 | // end::code[] 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadFuture.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.Future; 6 | 7 | public class Tasks_SingleThreadFuture { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | ExecutorService executor = null; 12 | try { 13 | executor = Executors.newSingleThreadExecutor(); 14 | Future tarefa = executor.submit(() -> System.out.println("Tarefa executando")); 15 | 16 | // verifica se a tarefa está finalizada 17 | System.out.println("Tarefa já finalizada? " + tarefa.isDone()); 18 | 19 | // tenta cancelar a tarefa 20 | System.out.println("Tentando cancelar a tarefa. Conseguiu? " + tarefa.cancel(true)); 21 | 22 | // verifica se a tarefa foi cancelada 23 | System.out.println("Tarefa foi cancelada? " + tarefa.isCancelled()); 24 | } finally { 25 | if (executor != null) { 26 | executor.shutdown(); 27 | } 28 | } 29 | // end::code[] 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadManyTasks.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class Tasks_SingleThreadManyTasks { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ExecutorService executor = null; 11 | try { 12 | executor = Executors.newSingleThreadExecutor(); // executor com uma única thread 13 | executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName())); 14 | executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName())); 15 | executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName())); 16 | System.out.println("Thread Principal: " + Thread.currentThread().getName()); 17 | } finally { 18 | if (executor != null) { 19 | executor.shutdown(); 20 | } 21 | } 22 | // end::code[] 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/executetasks/Tasks_SingleThreadSubmit.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.executetasks; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.Future; 6 | 7 | public class Tasks_SingleThreadSubmit { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | ExecutorService executor = null; 12 | try { 13 | executor = Executors.newSingleThreadExecutor(); 14 | Future tarefa = executor.submit(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName())); 15 | 16 | System.out.println("Tarefa já finalizada? " + tarefa.isDone()); 17 | System.out.println("Tarefa já finalizada? " + tarefa.isDone()); 18 | System.out.println("Tarefa já finalizada? " + tarefa.isDone()); 19 | System.out.println("Tarefa já finalizada? " + tarefa.isDone()); 20 | } finally { 21 | if (executor != null) { 22 | executor.shutdown(); 23 | } 24 | } 25 | // end::code[] 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_Fair.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Locks_Fair { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Lock lock = new ReentrantLock(true); // lock "justo" 11 | try { 12 | lock.lock(); 13 | System.out.println("ABC"); 14 | } finally { 15 | lock.unlock(); // desfaz o lock 16 | } 17 | // end::code[] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_LockTwice.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Locks_LockTwice { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Lock lock = new ReentrantLock(); 11 | try { 12 | lock.lock(); 13 | lock.lock(); 14 | System.out.println("ABC"); 15 | } finally { 16 | lock.unlock(); // desfaz o primeiro lock 17 | lock.unlock(); // desfaz o segundo lock 18 | } 19 | // end::code[] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Locks_ReentrantLock { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Lock lock = new ReentrantLock(); 11 | try { 12 | lock.lock(); // apenas uma thread obtém o lock por vez 13 | System.out.println("ABC"); 14 | } finally { 15 | lock.unlock(); // desfaz o lock 16 | } 17 | // end::code[] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_TryLock.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Locks_TryLock { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Lock lock = new ReentrantLock(); 11 | boolean temLock = lock.tryLock(); 12 | 13 | if (temLock) { 14 | try { 15 | System.out.println("ABC"); 16 | } finally { 17 | lock.unlock(); // desfaz o lock 18 | } 19 | } else { 20 | System.out.println("DEF"); 21 | } 22 | // end::code[] 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_TryLockTimeout.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class Locks_TryLockTimeout { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | Lock lock = new ReentrantLock(); 12 | 13 | boolean temLock = false; 14 | try { 15 | // tenta obter o lock por no máximo 1 segundo 16 | temLock = lock.tryLock(1, TimeUnit.SECONDS); 17 | } catch (InterruptedException e) { 18 | System.out.println("Não obteve o Lock"); 19 | } 20 | 21 | if (temLock) { 22 | try { 23 | System.out.println("ABC"); 24 | } finally { 25 | lock.unlock(); // desfaz o lock 26 | } 27 | } else { 28 | System.out.println("DEF"); 29 | } 30 | // end::code[] 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/org/j6toj8/concurrency/locks/Locks_UnlockWithoutLock.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.concurrency.locks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Locks_UnlockWithoutLock { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Lock lock = new ReentrantLock(); 11 | try { 12 | System.out.println("ABC"); 13 | } finally { 14 | lock.unlock(); // lança exceção, pois não há lock 15 | } 16 | // end::code[] 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/fileimprovements/Improvements_Find.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.fileimprovements; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class Improvements_Find { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | String userHome = System.getProperty("user.home"); 13 | Path path = Paths.get(userHome, "arquivos"); 14 | System.out.println("Path: " + path); 15 | 16 | try { 17 | System.out.println("\nTodos os arquivos, ignorando diretórios, até o segundo nível: "); 18 | // ao chamar o find: 19 | // primeiro argumento: o path inicial 20 | // segundo argumento: o limite de profundidade 21 | // terceiro argumento: expressão lambda para filtrar 22 | Files.find(path, 2, (p, a) -> a.isRegularFile()) 23 | .forEach(System.out::println); 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } 27 | // end::code[] 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/fileimprovements/Improvements_Lines.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.fileimprovements; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class Improvements_Lines { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | String userHome = System.getProperty("user.home"); 13 | Path path = Paths.get(userHome, "arquivos", "subpasta1", "arquivo11.txt"); 14 | System.out.println("Path: " + path); 15 | 16 | try { 17 | System.out.println("\nConteúdo do arquivo: "); 18 | Files.lines(path) // recupera todas as linhas do arquivo como Stream 19 | .forEach(System.out::println); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | try { 25 | System.out.println("\nConteúdo do arquivo maior que 2: "); 26 | Files.lines(path) 27 | .filter(s -> Integer.parseInt(s) > 2) // filtra maior que 2 28 | .forEach(System.out::println); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | // end::code[] 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/fileimprovements/Improvements_List.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.fileimprovements; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class Improvements_List { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | String userHome = System.getProperty("user.home"); 13 | Path path = Paths.get(userHome, "arquivos"); 14 | System.out.println("Path: " + path); 15 | 16 | try { 17 | System.out.println("\nListagem do diretório: "); 18 | Files.list(path) 19 | .forEach(System.out::println); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | try { 25 | System.out.println("\nListagem do diretório, apenas arquivos: "); 26 | Files.list(path) 27 | .filter(p -> Files.isRegularFile(p)) 28 | .forEach(System.out::println); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | 33 | // end::code[] 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/fileimprovements/Improvements_Walk.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.fileimprovements; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class Improvements_Walk { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | String userHome = System.getProperty("user.home"); 13 | Path path = Paths.get(userHome, "arquivos"); 14 | System.out.println("Path: " + path); 15 | 16 | try { 17 | System.out.println("\nTodos os arquivos e diretórios: "); 18 | Files.walk(path) // cria o stream 19 | .forEach(System.out::println); // imprime no console 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | try { 25 | System.out.println("\nOs primeiro 5 arquivos e diretórios: "); 26 | Files.walk(path) 27 | .limit(5) 28 | .forEach(System.out::println); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | 33 | // end::code[] 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/fileimprovements/Improvements_WalkDepth.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.fileimprovements; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.FileVisitOption; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | 9 | public class Improvements_WalkDepth { 10 | 11 | public static void main(String[] args) { 12 | // tag::code[] 13 | String userHome = System.getProperty("user.home"); 14 | Path path = Paths.get(userHome, "arquivos"); 15 | System.out.println("Path: " + path); 16 | 17 | try { 18 | System.out.println("\nArquivos e Links simbólicos até o segundo nível: "); 19 | Files.walk(path, 2, FileVisitOption.FOLLOW_LINKS) 20 | .forEach(System.out::println); 21 | } catch (IOException e) { 22 | e.printStackTrace(); 23 | } 24 | 25 | // end::code[] 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/files/Files_CreateDirectory.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.files; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.Random; 8 | 9 | public class Files_CreateDirectory { 10 | 11 | public static void main(String[] args) { 12 | // tag::code[] 13 | String userHome = System.getProperty("user.home"); 14 | System.out.println("User home: " + userHome); 15 | 16 | // Utilizando um nome aleatório de diretório, 17 | // apenas para o exemplo executar inúmeras vezes sem problemas 18 | String nomeAleatorio = "arquivo" + new Random().nextInt(); 19 | 20 | Path path = Paths.get(userHome, nomeAleatorio); 21 | System.out.println("Path: " + path); 22 | 23 | try { 24 | System.out.println("Path existe? " + Files.exists(path)); 25 | Files.createDirectory(path); 26 | System.out.println("Path existe? " + Files.exists(path)); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | 31 | // end::code[] 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/files/Files_CreateFile.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.files; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.Random; 8 | 9 | public class Files_CreateFile { 10 | 11 | public static void main(String[] args) { 12 | // tag::code[] 13 | String userHome = System.getProperty("user.home"); 14 | System.out.println("User home: " + userHome); 15 | 16 | // Utilizando um nome aleatório de arquivo, 17 | // apenas para o exemplo executar inúmeras vezes sem problemas 18 | String nomeAleatorio = "arquivo" + new Random().nextInt() + ".txt"; 19 | 20 | Path path = Paths.get(userHome, nomeAleatorio); 21 | System.out.println("Path: " + path); 22 | 23 | try { 24 | System.out.println("Path existe? " + Files.exists(path)); 25 | Files.createFile(path); 26 | System.out.println("Path existe? " + Files.exists(path)); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | 31 | // end::code[] 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/files/Files_ReadAllLines.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.files; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | public class Files_ReadAllLines { 10 | 11 | public static void main(String[] args) { 12 | // tag::code[] 13 | String userHome = System.getProperty("user.home"); 14 | System.out.println("User home: " + userHome); 15 | 16 | Path path = Paths.get(userHome, "arquivo.txt"); 17 | try { 18 | List conteudo = Files.readAllLines(path); 19 | System.out.println(conteudo); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | // end::code[] 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_CreationDoesntExists.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_CreationDoesntExists { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String userHome = System.getProperty("user.home"); 11 | System.out.println("User home: " + userHome); 12 | 13 | Path path = Paths.get(userHome, "arquivoQueNaoExiste.txt"); 14 | System.out.println("Path: " + path); 15 | // end::code[] 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_Names.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_Names { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String userHome = System.getProperty("user.home"); 11 | System.out.println("User home: " + userHome + "\n"); 12 | 13 | Path path = Paths.get(userHome, "arquivos", "arquivo.txt"); 14 | int nameCount = path.getNameCount(); // quantidade de elementos no Path 15 | for (int i = 0; i < nameCount; i++) { 16 | Path name = path.getName(i);// recupera o elemento específico 17 | System.out.println(name); 18 | } 19 | // end::code[] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_Normalize.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_Normalize { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String userHome = System.getProperty("user.home"); 11 | System.out.println("User home: " + userHome); 12 | 13 | System.out.println(); 14 | 15 | Path path1 = Paths.get(userHome, "arquivos/./arquivo1.txt"); 16 | System.out.println("Path: " + path1); 17 | System.out.println("Path normalize: " + path1.normalize()); 18 | 19 | System.out.println(); 20 | 21 | Path path2 = Paths.get(userHome, "arquivos/../arquivo1.txt"); 22 | System.out.println("Path: " + path2); 23 | System.out.println("Path normalize: " + path2.normalize()); 24 | 25 | // end::code[] 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_Resolve.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_Resolve { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String userHome = System.getProperty("user.home"); 11 | System.out.println("User home: " + userHome); 12 | 13 | System.out.println(); 14 | 15 | Path path1 = Paths.get(userHome, "arquivos"); 16 | Path path2 = Paths.get("arquivo1.txt"); 17 | System.out.println("Absoluto + Relativo: " + path1.resolve(path2)); 18 | System.out.println("Relativo + Absoluto: " + path2.resolve(path1)); 19 | System.out.println("Absoluto + Absoluto: " + path1.resolve(path1)); 20 | System.out.println("Relativo + Relativo: " + path2.resolve(path2)); 21 | // end::code[] 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_SubPath.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_SubPath { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String userHome = System.getProperty("user.home"); 11 | System.out.println("User home: " + userHome); 12 | 13 | Path path = Paths.get(userHome, "arquivos", "arquivo1.txt"); 14 | System.out.println("Path: " + path); 15 | 16 | Path subpath1 = path.subpath(0, 1); 17 | System.out.println(subpath1); 18 | 19 | Path subpath2 = path.subpath(0, 2); 20 | System.out.println(subpath2); 21 | 22 | Path subpath3 = path.subpath(1, 3); 23 | System.out.println(subpath3); 24 | 25 | Path subpath4 = path.subpath(2, 4); 26 | System.out.println(subpath4); 27 | 28 | Path subpath5 = path.subpath(3, 5); // EXCEÇÃO, pois só existem 4 elementos no path 29 | // end::code[] 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_ToAbsolute.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.nio.file.Path; 4 | import java.nio.file.Paths; 5 | 6 | public class Paths_ToAbsolute { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Path path = Paths.get("arquivos"); 11 | System.out.println(path); 12 | System.out.println("É absoluto? " + path.isAbsolute()); 13 | 14 | System.out.println(); 15 | 16 | Path absolutePath = path.toAbsolutePath(); 17 | System.out.println(absolutePath); 18 | System.out.println("É absoluto? " + absolutePath.isAbsolute()); 19 | // end::code[] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_ToFile.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.io.File; 4 | import java.nio.file.Path; 5 | import java.nio.file.Paths; 6 | 7 | public class Paths_ToFile { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | String userHome = System.getProperty("user.home"); 12 | System.out.println("User home: " + userHome); 13 | 14 | Path path = Paths.get(userHome, "arquivoQueNaoExiste.txt"); 15 | System.out.println("Path: " + path); 16 | 17 | File file = path.toFile(); 18 | System.out.println("File: " + file); 19 | // end::code[] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/paths/Paths_ToRealPath.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.paths; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Path; 5 | import java.nio.file.Paths; 6 | 7 | public class Paths_ToRealPath { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | String userHome = System.getProperty("user.home"); 12 | System.out.println("User home: " + userHome); 13 | 14 | Path pathQueExiste = Paths.get(userHome, "arquivo1.txt"); 15 | Path pathQueNaoExiste = Paths.get(userHome, "arquivoQueNaoExiste.txt"); 16 | 17 | try { 18 | Path realPath = pathQueExiste.toRealPath(); 19 | System.out.println("realPath: " + realPath); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | try { 25 | pathQueNaoExiste.toRealPath(); // LANÇA EXCEÇÃO 26 | } catch (IOException e) { 27 | e.printStackTrace(); 28 | } 29 | // end::code[] 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/org/j6toj8/fileio/watchservice/WatchService_File.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.fileio.watchservice; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.FileSystems; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.nio.file.StandardWatchEventKinds; 8 | import java.nio.file.WatchService; 9 | 10 | public class WatchService_File { 11 | 12 | public static void main(String[] args) { 13 | // tag::code[] 14 | String userHome = System.getProperty("user.home"); 15 | Path path = Paths.get(userHome, "arquivos", "arquivo1.txt"); // NÃO SUPORTADO 16 | System.out.println("Path: " + path); 17 | 18 | try (WatchService service = FileSystems.getDefault().newWatchService();) { 19 | path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); // LANÇA EXCEÇÃO 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | // end::code[] 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerExample.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalTime; 5 | import java.util.function.BiConsumer; 6 | import java.util.function.Consumer; 7 | 8 | public class BuiltInInterfaces_ConsumerExample { 9 | 10 | // tag::code[] 11 | public static void main(String[] args) { 12 | Consumer impressor = x -> System.out.println(x); 13 | impressor.accept(LocalDate.now()); // imprimirá a data atual 14 | 15 | BiConsumer impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); }; 16 | impressor2.accept(LocalDate.now(), LocalTime.now()); // imprimirá a data atual e depois a hora atual 17 | } 18 | // end::code[] 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_ConsumerPrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.time.LocalDate; 4 | import java.util.function.IntConsumer; 5 | import java.util.function.ObjIntConsumer; 6 | 7 | public class BuiltInInterfaces_ConsumerPrimitive { 8 | 9 | // tag::code[] 10 | public static void main(String[] args) { 11 | IntConsumer impressor = x -> System.out.println(x); 12 | impressor.accept(5); // imprimirá '5' 13 | 14 | ObjIntConsumer impressor2 = (x, y) -> { System.out.println(x); System.out.println(y); }; 15 | impressor2.accept(LocalDate.now(), 5); // imprimirá a data atual e depois '5' 16 | } 17 | // end::code[] 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionExample.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.function.BiFunction; 4 | import java.util.function.Function; 5 | 6 | public class BuiltInInterfaces_FunctionExample { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | Function duplica = x -> x * 2.5; 11 | System.out.println(duplica.apply(3)); // multiplica 3 * 2.5 12 | 13 | BiFunction multiplicaEDuplica = (x, y) -> x * y * 2.5; 14 | System.out.println(multiplicaEDuplica.apply(3, 4)); // multiplica 3 * 4 * 2.5 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_FunctionPrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.function.IntToDoubleFunction; 4 | import java.util.function.ToDoubleBiFunction; 5 | 6 | public class BuiltInInterfaces_FunctionPrimitive { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | IntToDoubleFunction duplica = x -> x * 2.5; 11 | System.out.println(duplica.applyAsDouble(3)); // multiplica 3 * 2.5 12 | 13 | ToDoubleBiFunction multiplicaEDuplica = (x, y) -> x * y * 2.5; 14 | System.out.println(multiplicaEDuplica.applyAsDouble(3, 4)); // multiplica 3 * 4 * 2.5 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorExample.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.function.BinaryOperator; 4 | import java.util.function.UnaryOperator; 5 | 6 | public class BuiltInInterfaces_OperatorExample { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | UnaryOperator somaDois = x -> x + 2; 11 | System.out.println(somaDois.apply(7)); // soma 7 + 2 12 | 13 | BinaryOperator somaNumeros = (x, y) -> x + y; 14 | System.out.println(somaNumeros.apply(1, 5)); // soma 1 + 5 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OperatorPrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.function.IntBinaryOperator; 4 | import java.util.function.IntUnaryOperator; 5 | 6 | public class BuiltInInterfaces_OperatorPrimitive { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | IntUnaryOperator somaDois = x -> x + 2; 11 | System.out.println(somaDois.applyAsInt(7)); // soma 7 + 2 12 | 13 | IntBinaryOperator somaNumeros = (x, y) -> x + y; 14 | System.out.println(somaNumeros.applyAsInt(1, 5)); // soma 1 + 5 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalGetEmpty.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Optional; 4 | 5 | public class BuiltInInterfaces_OptionalGetEmpty { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Optional optionalComValor = Optional.of("valor"); 10 | System.out.println(optionalComValor.get()); // recupera o valor corretamente 11 | 12 | Optional optionalVazio = Optional.empty(); 13 | System.out.println(optionalVazio.get()); // lança exceção 14 | // end::code[] 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalIfPresent.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Optional; 4 | 5 | public class BuiltInInterfaces_OptionalIfPresent { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | Optional optionalVazio = Optional.empty(); 10 | Optional optionalComValor = Optional.of("valor"); 11 | 12 | // A linha abaixo não irá imprimir nada, pois o optional está vazio 13 | optionalVazio.ifPresent(valor -> System.out.println("Vazio: " + valor)); 14 | // A linha abaixo irá imprimir, pois o optional possui valor 15 | optionalComValor.ifPresent(valor -> System.out.println("Com Valor: " + valor )); 16 | } 17 | // end::code[] 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalNullable.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Optional; 4 | 5 | public class BuiltInInterfaces_OptionalNullable { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | // Exemplo tentando utilizar .of e passando 'null' como argumento 10 | try { 11 | Optional.of(null); // Lança NullPointerException nesta linha 12 | } catch (Exception e) { 13 | e.printStackTrace(); 14 | } 15 | 16 | // Exemplo utilizando o método correto: .ofNullable 17 | Optional ofNullable = Optional.ofNullable(null); // Cria um Optional vazio 18 | System.out.println(ofNullable.isPresent()); // Imprime 'false' pois não possui valor 19 | } 20 | // end::code[] 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalOrElseThrow.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Optional; 4 | 5 | public class BuiltInInterfaces_OptionalOrElseThrow { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | Optional optionalVazio = Optional.empty(); 10 | Optional optionalComValor = Optional.of("valor"); 11 | 12 | // Nesse caso será impresso o valor presente em Optional, pois ele está preenchido 13 | String orElseThrow1 = optionalComValor.orElseThrow(() -> new RuntimeException()); 14 | System.out.println(orElseThrow1); 15 | 16 | // Nesse caso será lançada exceção, pois o Optional não está preenchido 17 | String orElseThrow2 = optionalVazio.orElseThrow(() -> new RuntimeException()); 18 | } 19 | // end::code[] 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_OptionalPrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.OptionalInt; 4 | 5 | public class BuiltInInterfaces_OptionalPrimitive { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | OptionalInt optionalComValor = OptionalInt.of(5); 10 | OptionalInt optionalVazio = OptionalInt.empty(); 11 | 12 | if (optionalComValor.isPresent()) { 13 | System.out.println(optionalComValor.getAsInt()); 14 | } 15 | if (optionalVazio.isPresent()) { 16 | System.out.println(optionalVazio.getAsInt()); 17 | } 18 | // end::code[] 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicateExample.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Random; 4 | import java.util.function.BiPredicate; 5 | import java.util.function.Predicate; 6 | 7 | public class BuiltInInterfaces_PredicateExample { 8 | 9 | // tag::code[] 10 | public static void main(String[] args) { 11 | Predicate dado = x -> x.equals(new Random().nextInt(7)); 12 | System.out.println(dado.test(1)); // testa se o número gerado é igual a 1 13 | 14 | BiPredicate dadoDuplo = (x, y) -> x.equals(new Random().nextInt(7)) || y.equals(new Random().nextInt(7)); 15 | System.out.println(dadoDuplo.test(1, 2)); // testa se o primeiro número gerado é igual a 1 16 | // ou se o segundo número gerado é igual a 2 17 | } 18 | // end::code[] 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_PredicatePrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Random; 4 | import java.util.function.IntPredicate; 5 | 6 | public class BuiltInInterfaces_PredicatePrimitive { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | IntPredicate dado = x -> x == new Random().nextInt(7); 11 | System.out.println(dado.test(1)); // testa se o número gerado é igual a 1 12 | } 13 | // end::code[] 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierExample.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.time.LocalDate; 4 | import java.util.function.Supplier; 5 | 6 | public class BuiltInInterfaces_SupplierExample { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | Supplier supplier = () -> LocalDate.now(); 11 | System.out.println(supplier.get()); // imprimirá a data atual 12 | } 13 | // end::code[] 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierPrimitive.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.util.Random; 4 | import java.util.function.IntSupplier; 5 | 6 | public class BuiltInInterfaces_SupplierPrimitive { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | IntSupplier randomIntSupplier = () -> new Random().nextInt(); 11 | System.out.println(randomIntSupplier.getAsInt()); // getAsInt retorna um int primitivo 12 | } 13 | // end::code[] 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/builtininterfaces/BuiltInInterfaces_SupplierUseCase.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.builtininterfaces; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalTime; 5 | import java.time.format.DateTimeFormatter; 6 | import java.util.function.Supplier; 7 | 8 | public class BuiltInInterfaces_SupplierUseCase { 9 | 10 | // tag::code[] 11 | public static String valideIdade(int idade, Supplier supplier) { 12 | if (idade < 18) { 13 | return "Menor de idade!"; 14 | } else { 15 | return "Maior de idade! Validação realizada às " + supplier.get(); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | Supplier supplier = () -> LocalDate.now().atTime(LocalTime.now()).format(DateTimeFormatter.ISO_DATE_TIME); 21 | System.out.println(valideIdade(17, supplier)); 22 | System.out.println(valideIdade(18, supplier)); 23 | } 24 | // end::code[] 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Basic.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_Basic { 4 | 5 | // tag::code[] 6 | @FunctionalInterface // a anotação não é obrigatória 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | } 10 | // end::code[] 11 | } 12 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ClassCompilationError.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_ClassCompilationError { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | } 10 | 11 | @FunctionalInterface 12 | class Piloto { // NÃO COMPILA! 13 | // apenas interfaces podem ser anotadas com @FunctionalInterface 14 | } 15 | // end::code[] 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_DefaultStatic.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_DefaultStatic { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | 10 | // métodos adicionais static são permitidos 11 | static void execute(Executavel... executaveis) { 12 | for (Executavel executavel : executaveis) { 13 | executavel.execute(); 14 | } 15 | } 16 | 17 | // métodos adicionais default são permitidos 18 | default void executeDuasVezes() { 19 | execute(); 20 | execute(); 21 | } 22 | } 23 | // end::code[] 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Extends.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_Extends { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | } 10 | 11 | @FunctionalInterface 12 | interface Aplicacao extends Executavel { 13 | // também é uma interface funcional 14 | } 15 | // end::code[] 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ExtendsNewMethod.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_ExtendsNewMethod { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | } 10 | 11 | interface Aplicacao extends Executavel { 12 | // NÃO é uma interface funcional, pois possui 2 métodos abstratos: execute (herdado) e inicie. 13 | void inicie(); 14 | } 15 | // end::code[] 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_Implement.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_Implement { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | String execute(); // método funcional 9 | } 10 | 11 | class Pessoa implements Executavel { 12 | // COMPILA! 13 | // interfaces funcionais, como Executavel, não foram feitas para serem implementadas dessa forma 14 | // porém é possível e o código compila normalmente 15 | @Override 16 | public String execute() { 17 | return "Executando"; 18 | } 19 | } 20 | // end::code[] 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_InterfaceCompilationError.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_InterfaceCompilationError { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | } 10 | 11 | @FunctionalInterface 12 | interface Aplicacao extends Executavel { // NÃO COMPILA! 13 | // não pode ser anotada como funcional, pois possui 2 métodos abstratos 14 | void inicie(); 15 | } 16 | // end::code[] 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_OverrideObject.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_OverrideObject { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | void execute(); // método funcional 9 | 10 | // sobrescrevendo métodos de Object 11 | @Override 12 | String toString(); 13 | @Override 14 | boolean equals(Object obj); 15 | @Override 16 | int hashCode(); 17 | } 18 | // end::code[] 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/functionalinterfaces/FunctionalInterfaces_ReturnType.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.functionalinterfaces; 2 | 3 | public class FunctionalInterfaces_ReturnType { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | String execute(); // método funcional com retorno 9 | } 10 | // end::code[] 11 | } 12 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AccessExternalVar.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.UnaryOperator; 4 | 5 | public class LambdaExpression_AccessExternalVar { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | final Double x1 = 2.0; 10 | Double x2 = 2.0; 11 | Double x3 = 2.0; 12 | 13 | // COMPILA - variável externa 'x1' é final e pode ser utilizada na expressão lambda 14 | UnaryOperator elevarAoX1 = (Double y) -> Math.pow(y, x1); 15 | 16 | // COMPILA - variável externa 'x2' não é final, mas nunca é alterada, então pode ser utilizada dentro da expressão lambda 17 | UnaryOperator elevarAoX2 = (Double y) -> Math.pow(y, x2); 18 | 19 | // NÃO COMPILA - variável externa 'x3' é alterada dentro desse método, então não pode ser utilizada dentro da expressão lambda 20 | UnaryOperator elevarAoX3 = (Double y) -> Math.pow(y, x3); 21 | 22 | x3 = 3.0; // alteração da variável x3 não permite que ela seja utilizada em expressões lambda 23 | } 24 | // end::code[] 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Ambiguity.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | public class LambdaExpression_Ambiguity { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Corredor { 8 | void corra(); 9 | } 10 | 11 | @FunctionalInterface 12 | interface Piloto { 13 | void corra(); 14 | } 15 | 16 | static class Executor { 17 | void execute(Corredor corredor) { 18 | corredor.corra(); 19 | } 20 | 21 | String execute(Piloto piloto) { 22 | piloto.corra(); 23 | return "correndo"; 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | Executor executor = new Executor(); 29 | // NÃO COMPILA - não é possível determinar o tipo da expressão lambda abaixo 30 | executor.execute(() -> System.out.println("execute")); 31 | } 32 | // end::code[] 33 | } 34 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_AnonymousClass.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | public class LambdaExpression_AnonymousClass { 4 | 5 | public static void main(String[] args) { 6 | // tag::code[] 7 | // com classe anônima 8 | new Thread(new Runnable() { 9 | @Override 10 | public void run() { 11 | System.out.println("Executando."); 12 | } 13 | }).run(); 14 | 15 | // com expressão lambda 16 | new Thread(() -> System.out.println("Executando.")).run(); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Block.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.Consumer; 4 | import java.util.function.UnaryOperator; 5 | 6 | public class LambdaExpression_Block { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | UnaryOperator elevarAoQuadrado = (Double x) -> { 11 | double pow = Math.pow(x, 2); 12 | return pow; 13 | }; 14 | 15 | Consumer imprime = (Double x) -> { 16 | double pow = Math.pow(x, 2); 17 | System.out.println(pow); 18 | }; 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_ForEach.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class LambdaExpression_ForEach { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List lista = Arrays.asList(1, 2, 3, 4, 5); 11 | lista.forEach((numero) -> { System.out.println(numero); }); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_FunctionalInterface.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | public class LambdaExpression_FunctionalInterface { 4 | 5 | // tag::code[] 6 | @FunctionalInterface 7 | interface Executavel { // interface funcional 8 | String execute(); // método funcional 9 | } 10 | 11 | private static void executeEApresenteMensagem(Executavel executavel) { 12 | String mensagem = executavel.execute(); 13 | System.out.println(mensagem); 14 | } 15 | 16 | public static void main(String[] args) { 17 | 18 | // com classe anônima 19 | executeEApresenteMensagem(new Executavel() { 20 | @Override 21 | public String execute() { 22 | return "executei com classe anônima"; 23 | } 24 | }); 25 | 26 | // com expressão lambda 27 | executeEApresenteMensagem(() -> { return "executei com expressão lambda"; }); 28 | } 29 | // end::code[] 30 | } 31 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Parenthesis.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.UnaryOperator; 4 | 5 | public class LambdaExpression_Parenthesis { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // NÃO COMPILA - parênteses são obrigatórios ao declarar o tipo da variável da expressão lambda 10 | UnaryOperator elevarAoQuadrado = Double x -> Math.pow(x, 2); 11 | 12 | // NÃO COMPILA - é obrigatório utilizar parênteses quando há mais de uma variável na expressão lambda 13 | BinaryOperator elevarAoX = y, x -> Math.pow(y, x); 14 | 15 | // NÃO COMPILA - é obrigatório utilizar parênteses quando não há variáveis 16 | Supplier elevar2aoQuadrado = -> Math.pow(2, 2); 17 | 18 | // COMPILA - parênteses vazios quando não há variáveis 19 | Supplier elevar2aoQuadrado = () -> Math.pow(2, 2); 20 | 21 | // COMPILA - sem parênteses quando há apenas uma variável e não escrevemos seu tipo 22 | UnaryOperator elevarAoQuadrado2 = x -> Math.pow(x, 2); 23 | // end::code[] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_Shadowing.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.BinaryOperator; 4 | import java.util.function.UnaryOperator; 5 | 6 | public class LambdaExpression_Shadowing { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) { 10 | Double x = 2.0; // variável 'x' no método 11 | 12 | // NÃO COMPILA - a variável com nome 'x' já existe e não pode ser declarada nas variáveis da expressão lambda 13 | BinaryOperator elevarAoX = (Double y, Double x) -> Math.pow(y, x); 14 | 15 | // NÃO COMPILA - a variável com nome 'x' já existe e não pode ser declarada no corpo da expressão lambda 16 | UnaryOperator elevarAoQuadrado = (Double y) -> { 17 | Double x = 2.0; 18 | return Math.pow(y, x); 19 | }; 20 | } 21 | // end::code[] 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_SimpleComplete.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.UnaryOperator; 4 | 5 | public class LambdaExpression_SimpleComplete { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // expressão lambda completa 10 | UnaryOperator elevarAoQuadrado1 = (Double x) -> { return Math.pow(x, 2); }; 11 | // expressão lambda simplificada 12 | UnaryOperator elevarAoQuadrado2 = (x) -> Math.pow(x, 2); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/lambdaexpression/LambdaExpression_VarType.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.lambdaexpression; 2 | 3 | import java.util.function.BinaryOperator; 4 | 5 | public class LambdaExpression_VarType { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // NÃO COMPILA - caso o tipo de um dos parâmetros for informado, é necessário informar de todos eles 10 | BinaryOperator elevarAoX = (Double y, x) -> Math.pow(y, x); 11 | 12 | // COMPILA - todos os parâmetros com tipos informados 13 | BinaryOperator elevarAoX2 = (Double y, Double x) -> Math.pow(y, x); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Complex.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.Function; 4 | 5 | public class MethodReference_Complex { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Function stringParaInteger1 = s -> new Integer(s + "2"); 10 | System.out.println(stringParaInteger1.apply("1")); 11 | // end::code[] 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.Function; 4 | 5 | public class MethodReference_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // representação com expressão lambda 10 | Function stringParaInteger1 = s -> new Integer(s); 11 | // representação com referência ao construtor 12 | Function stringParaInteger2 = Integer::new; 13 | 14 | // os resultados serão iguais 15 | System.out.println(stringParaInteger1.apply("1")); 16 | System.out.println(stringParaInteger2.apply("1")); 17 | // end::code[] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Instance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | public class MethodReference_Instance { 6 | 7 | // tag::code[] 8 | static class Conversor { 9 | public String converte(Integer x, Integer y) { 10 | return String.valueOf(x) + " - " + String.valueOf(y); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | Conversor conversor = new Conversor(); // instância da classe Conversor 16 | 17 | // representação com expressão lambda 18 | BiFunction converte1 = (x, y) -> conversor.converte(x, y); 19 | // representação com referência ao método da instância 20 | BiFunction converte2 = conversor::converte; 21 | 22 | // os resultados serão iguais 23 | System.out.println(converte1.apply(5, 8)); 24 | System.out.println(converte2.apply(5, 8)); 25 | } 26 | // end::code[] 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Static.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.Function; 4 | 5 | public class MethodReference_Static { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // representação com expressão lambda 10 | Function converteIntEmStr1 = x -> String.valueOf(x); 11 | // representação com referência ao método 12 | Function converteIntEmStr2 = String::valueOf; 13 | 14 | System.out.println(converteIntEmStr1.apply(5)); 15 | System.out.println(converteIntEmStr2.apply(5)); 16 | // end::code[] 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Type.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.Function; 4 | 5 | public class MethodReference_Type { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // representação com expressão lambda 10 | Function intParaDouble1 = x -> x.doubleValue(); 11 | // representação com referência ao método doubleValue 12 | Function intParaDouble2 = Integer::doubleValue; 13 | 14 | // os resultados serão iguais 15 | System.out.println(intParaDouble1.apply(8)); 16 | System.out.println(intParaDouble2.apply(8)); 17 | // end::code[] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_TypeWithParam.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | public class MethodReference_TypeWithParam { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // representação com expressão lambda 10 | BiFunction comparador1 = (x, y) -> x.compareTo(y); 11 | // representação com referência ao método compareTo do tipo Integer (que recebe um parâmetro) 12 | BiFunction comparador2 = Integer::compareTo; 13 | 14 | // os resultados serão iguais 15 | System.out.println(comparador1.apply(1, 2)); 16 | System.out.println(comparador2.apply(1, 2)); 17 | // end::code[] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/lambda/methodreference/MethodReference_Variaty.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.lambda.methodreference; 2 | 3 | import java.util.function.Function; 4 | 5 | public class MethodReference_Variaty { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // ATENÇÃO! Todas essas expressões lambda são equivalentes! 10 | 11 | Function lambda1 = (Integer x) -> { return String.valueOf(x); }; 12 | Function lambda2 = (x) -> { return String.valueOf(x); }; 13 | Function lambda3 = x -> { return String.valueOf(x); }; 14 | 15 | Function lambda4 = (Integer x) -> String.valueOf(x); 16 | Function lambda5 = (x) -> String.valueOf(x); 17 | Function lambda6 = x -> String.valueOf(x); 18 | 19 | Function lambda7 = String::valueOf; 20 | // end::code[] 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/literals/Literals_Complete.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.literals; 2 | 3 | public class Literals_Complete { 4 | 5 | public static void main(String[] args) { 6 | 7 | // tag::code[] 8 | int i1 = 1; // int 9 | int i2 = 1_000_000; // int com underscore 10 | int i3 = 0567; // octal 11 | int i4 = 0xFA1; // hexadecimal 12 | int i5 = 0b0101; // binário 13 | 14 | long l1 = 1L; // long com L 15 | long l2 = 1l; // long com l 16 | long l3 = 12_345_6_7890_123456_789L; // long com underscore 17 | long l4 = 0xFA1L; // long hexadecimal 18 | 19 | double d1 = 1.00; // double 20 | double d2 = 100_000.01; // double com underscore 21 | double d3 = 1D; // double com D 22 | double d4 = 3.1E2; // notação científica = 3.1 * 10^2 = 3.1 * 100 = 310.0 23 | 24 | float f1 = 1.00F; // float 25 | // end::code[] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/literals/Literals_Prefix.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.literals; 2 | 3 | public class Literals_Prefix { 4 | 5 | public static void main(String[] args) { 6 | 7 | // tag::code[] 8 | int i1 = 0567; // octal - base 8 - começa com 0 9 | int i2 = 0xFA1; // hexadecimal - base 16 - começa com 0x 10 | int i3 = 0b0101; // binário - base 2 - começa com 0b 11 | 12 | long l1 = 0xABCL; // long também pode ser hexadecimal - começa com 0x e termina com L 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/literals/Literals_Suffix.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.literals; 2 | 3 | public class Literals_Suffix { 4 | 5 | public static void main(String[] args) { 6 | 7 | // tag::code[] 8 | int i1 = 1; // por padrão é int 9 | long l1 = 1L; // com um L no final, é um long 10 | double d1 = 1.0; 11 | double d2 = 1.0D; // com ou sem D no final, se tiver casa decimal é um double por padrão 12 | float f1 = 1.0F; // com um F no final, é um float 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | import java.io.IOException; 4 | 5 | public class MultipleException_CheckedException { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | 10 | try { 11 | throw new NullPointerException(); 12 | } catch (NullPointerException | IOException e) { // NÃO COMPILA - IOException não é lançada dentro do bloco try 13 | System.out.println("Exceção capturada: " + e); 14 | } 15 | } 16 | // end::code[] 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | public class MultipleException_Complete { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | try { 9 | throw new NullPointerException(); 10 | } catch (NullPointerException | IllegalArgumentException | IllegalStateException e) { 11 | System.out.println("Exceção capturada: " + e); 12 | } catch (Exception e) { 13 | System.out.println("Exceção capturada: " + e); 14 | } 15 | } 16 | // end::code[] 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | public class MultipleException_GenericsLower { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | try { 9 | throw new NullPointerException(); 10 | } catch (Exception e) { 11 | System.out.println("Exceção capturada: " + e); 12 | } catch (NullPointerException | IllegalArgumentException e) { // NÃO COMPILA - NullPointerException é mais específico que Exception, logo deveria ser capturada antes de Exception 13 | System.out.println("Exceção capturada: " + e); 14 | } 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | import java.util.ConcurrentModificationException; 4 | 5 | public class MultipleException_MultipleSameCatch { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | 10 | try { 11 | throw new NullPointerException(); 12 | } catch (NullPointerException | IllegalArgumentException e) { // COMPILA - múltiplas exceções no mesmo catch, só uma variável no final 13 | System.out.println("Exceção capturada: " + e); 14 | } catch (IllegalStateException ise | UnsupportedOperationException uoe) { // NÃO COMPILA - mais de uma variável declarada 15 | System.out.println("Exceção capturada: " + ise); 16 | } catch (ClassCastException cce | ConcurrentModificationException) { // NÃO COMPILA - só uma variável, mas no lugar errado 17 | System.out.println("Exceção capturada: " + cce); 18 | } 19 | } 20 | // end::code[] 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | public class MultipleException_OverrideVar { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | try { 9 | throw new NullPointerException(); 10 | } catch (NullPointerException | IllegalArgumentException e) { 11 | e = new IllegalStateException(); // NÃO COMPILA - a variável não pode ser sobrescrita quando está em um multi-catch 12 | } catch (Exception e) { 13 | e = new IllegalStateException(); // COMPILA - ainda é possível sobrescrever a variável quando não é um multi-catch 14 | } 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | import java.util.ConcurrentModificationException; 4 | 5 | public class MultipleException_Redundant { 6 | 7 | // tag::code[] 8 | public static void main(String[] args) { 9 | 10 | try { 11 | throw new NullPointerException(); 12 | } catch (RuntimeException | IllegalArgumentException e) { // NÃO COMPILA - IllegalArgumentException herda de RuntimeException, logo seria redundante 13 | System.out.println("Exceção capturada: " + e); 14 | } 15 | } 16 | // end::code[] 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.multipleexception; 2 | 3 | public class MultipleException_RepeatException { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | try { 9 | throw new NullPointerException(); 10 | } catch (NullPointerException | IllegalArgumentException e) { 11 | System.out.println("Exceção capturada: " + e); 12 | } catch (IllegalStateException | NullPointerException e) { // NÃO COMPILA - NullPointerException já foi capturada no catch anterior 13 | System.out.println("Exceção capturada: " + e); 14 | } 15 | } 16 | // end::code[] 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Abstract.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | import java.io.IOException; 4 | 5 | public class StaticDefaultInInterfaces_Abstract { 6 | 7 | // tag::code[] 8 | interface Corredor { 9 | default String correr() { // COMPILA - método default não é abstract 10 | return "Correndo"; 11 | } 12 | 13 | abstract default String correrRapido() { // NÃO COMPILA - método default não pode ser declarado abstract 14 | return "Correndo Rápido"; 15 | } 16 | 17 | String correrDevagar(); // COMPILA - método comum, é abstract por padrão, mesmo que de forma implícita 18 | 19 | abstract String correrExtremo(); // COMPILA - método comum, declarado abstract de forma explícita 20 | 21 | abstract static double calculeVelocidade(int d, int t) { // NÃO COMPILA - método static não pode ser declarado abstract 22 | return d / t; 23 | } 24 | } 25 | // end::code[] 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_AccessModifiers.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | import java.io.IOException; 4 | 5 | public class StaticDefaultInInterfaces_AccessModifiers { 6 | 7 | // tag::code[] 8 | interface Corredor { 9 | default String correr() { // COMPILA - não há modificador de acesso declarado, é automaticamente público 10 | return "Correndo"; 11 | } 12 | public default String correrRapido() { // COMPILA - modificador de acesso público explícito 13 | return "Correndo Rápido"; 14 | } 15 | protected default String correrDevagar() { // NÃO COMPILA - o método deve ser obrigatoriamente público 16 | return "Correndo Devagar"; 17 | } 18 | private default String correrExtremo() { // NÃO COMPILA - o método deve ser obrigatoriamente público 19 | return "Correndo ao Extremo"; 20 | } 21 | 22 | private static double calculeVelocidade(int d, int t) { // NÃO COMPILA - o método deve ser obrigatoriamente público 23 | return d / t; 24 | } 25 | } 26 | // end::code[] 27 | } 28 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Complete.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | import java.io.IOException; 4 | 5 | public class StaticDefaultInInterfaces_Complete { 6 | 7 | // tag::code[] 8 | interface Corredor { 9 | static double calculeVelocidade(int distancia, int tempo) { 10 | return distancia / tempo; 11 | } 12 | 13 | default String correr() { 14 | return "Correndo"; 15 | } 16 | 17 | String correrRapido(); 18 | } 19 | 20 | static class Pessoa implements Corredor { 21 | @Override 22 | public String correrRapido() { 23 | return "Pessoa Correndo Rápido"; 24 | } 25 | 26 | public static void main(String[] args) throws IOException { 27 | System.out.println(Corredor.calculeVelocidade(100, 10)); 28 | System.out.println(new Pessoa().correr()); 29 | System.out.println(new Pessoa().correrRapido()); 30 | } 31 | } 32 | // end::code[] 33 | } 34 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Default.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | import java.io.IOException; 4 | 5 | public class StaticDefaultInInterfaces_Default { 6 | 7 | // tag::code[] 8 | interface Corredor { 9 | default String correr() { 10 | return "Correndo"; 11 | } 12 | } 13 | 14 | static class Pessoa implements Corredor { 15 | 16 | } 17 | 18 | static class Cavalo implements Corredor { 19 | @Override 20 | public String correr() { 21 | return "Galopando"; 22 | } 23 | 24 | public static void main(String[] args) throws IOException { 25 | System.out.println(new Pessoa().correr()); 26 | System.out.println(new Cavalo().correr()); 27 | } 28 | } 29 | // end::code[] 30 | } 31 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_InterfaceInheritance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | public class StaticDefaultInInterfaces_InterfaceInheritance { 4 | 5 | // tag::code[] 6 | interface Corredor { 7 | default String correr() { 8 | return "Correndo"; 9 | } 10 | default String correrRapido() { 11 | return "Correndo Rápido"; 12 | } 13 | default String correrDevagar() { 14 | return "Correndo Devagar"; 15 | } 16 | } 17 | 18 | interface Piloto extends Corredor { 19 | String correrRapido(); 20 | 21 | default String correrDevagar() { 22 | return "Piloto Correndo Devagar"; 23 | } 24 | } 25 | // end::code[] 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefault.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | public class StaticDefaultInInterfaces_RepeatedDefault { 4 | 5 | // tag::code[] 6 | interface Corredor { 7 | default String correr() { 8 | return "Correndo"; 9 | } 10 | } 11 | 12 | interface Piloto { 13 | default String correr() { 14 | return "Piloto Correndo"; 15 | } 16 | } 17 | 18 | static class Pessoa implements Corredor, Piloto { // NÃO COMPILA - implementa duas interfaces com métodos repetidos e não sobrescreve 19 | 20 | } 21 | 22 | static class Gigante implements Corredor, Piloto { // COMPILA - implementa duas interfaces com métodos repetidos, mas sobrescreve e cria sua própria implementação 23 | @Override 24 | public String correr() { 25 | return "Gigante Correndo"; 26 | } 27 | } 28 | // end::code[] 29 | } 30 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_RepeatedDefaultSuper.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | public class StaticDefaultInInterfaces_RepeatedDefaultSuper { 4 | 5 | // tag::code[] 6 | interface Corredor { 7 | default String correr() { 8 | return "Correndo"; 9 | } 10 | } 11 | 12 | interface Piloto { 13 | default String correr() { 14 | return "Piloto Correndo"; 15 | } 16 | } 17 | 18 | static class Pessoa implements Corredor, Piloto { // COMPILA - mantém a implementação do Corredor no método correr() 19 | @Override 20 | public String correr() { 21 | return Corredor.super.correr(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(new Pessoa().correr()); 26 | } 27 | } 28 | // end::code[] 29 | } 30 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/staticdefaultininterfaces/StaticDefaultInInterfaces_Static.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.staticdefaultininterfaces; 2 | 3 | import java.io.IOException; 4 | 5 | public class StaticDefaultInInterfaces_Static { 6 | 7 | // tag::code[] 8 | interface Corredor { 9 | static double calculeVelocidade(int distancia, int tempo) { 10 | return distancia / tempo; 11 | } 12 | } 13 | 14 | static class Pessoa implements Corredor { 15 | public static void main(String[] args) throws IOException { 16 | System.out.println(Corredor.calculeVelocidade(100, 50)); // COMPILA - método static de uma interface sendo chamado como se fosse de uma classe comum 17 | System.out.println(Pessoa.calculeVelocidade(100, 50)); // NÃO COMPILA - o método static não é herdado, nem implementado, pela classe Pessoa 18 | } 19 | } 20 | // end::code[] 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Break.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.stringinswitch; 2 | 3 | public class StringInSwitch_Break { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | String mes = "jan"; 9 | 10 | switch (mes) { 11 | case "jan": 12 | System.out.println("Janeiro"); 13 | default: 14 | System.out.println("Não é um mês"); 15 | case "fev": 16 | System.out.println("Fevereiro"); 17 | break; 18 | case "mar": 19 | System.out.println("Março"); 20 | break; 21 | } 22 | } 23 | // end::code[] 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Complete.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.stringinswitch; 2 | 3 | public class StringInSwitch_Complete { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | String mes = "jan"; 9 | 10 | switch (mes) { 11 | case "jan": 12 | System.out.println("Janeiro"); 13 | break; 14 | case "fev": 15 | System.out.println("Fevereiro"); 16 | break; 17 | case "mar": 18 | System.out.println("Março"); 19 | break; 20 | default: 21 | break; 22 | } 23 | } 24 | // end::code[] 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Default.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.stringinswitch; 2 | 3 | public class StringInSwitch_Default { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | String mes = "jan"; 9 | 10 | switch (mes) { 11 | case "jan": 12 | System.out.println("Janeiro"); 13 | break; 14 | default: // COMPILA - O default pode estar em qualquer posição 15 | break; 16 | case "jan": // NÃO COMPILA - Já existe o case "jan" 17 | System.out.println("Janeiro2"); 18 | break; 19 | case "mar": 20 | System.out.println("Março"); 21 | break; 22 | } 23 | } 24 | // end::code[] 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Empty.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.stringinswitch; 2 | 3 | public class StringInSwitch_Empty { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | String mes = "jan"; 9 | switch (mes) {} // COMPILA - switch pode estar vazio, mesmo que seja inútil 10 | } 11 | // end::code[] 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/stringinswitch/StringInSwitch_Type.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.stringinswitch; 2 | 3 | public class StringInSwitch_Type { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | 8 | Long mes = 1L; 9 | 10 | switch (mes) { // NÃO COMPILA - Long não é um tipo suportado 11 | case 1L: 12 | System.out.println("Janeiro"); 13 | break; 14 | case 2L: 15 | System.out.println("Fevereiro"); 16 | break; 17 | default: 18 | break; 19 | } 20 | } 21 | // end::code[] 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | import java.io.FileNotFoundException; 4 | 5 | public class TryWithResouces_AutoCloseable { 6 | 7 | // tag::code[] 8 | static class Porta implements AutoCloseable { 9 | @Override 10 | public void close() { // chamado automaticamente pelo try-with-resources 11 | System.out.println("Porta fechada."); 12 | } 13 | } 14 | 15 | public static void main(String[] args) throws FileNotFoundException { 16 | try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources 17 | System.out.println("try"); 18 | } 19 | } 20 | // end::code[] 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_CloseException { 4 | 5 | // tag::code[] 6 | static class Porta implements AutoCloseable { 7 | @Override 8 | public void close() throws Exception { // declara throws Exception obrigatoriamente 9 | throw new Exception(); 10 | } 11 | } 12 | 13 | void try1() { 14 | try (Porta porta = new Porta()) { // NÃO COMPILA - exceção do close() não é capturada nem declarada 15 | System.out.println("Olá 1"); 16 | } 17 | } 18 | 19 | void try2() { 20 | try (Porta porta = new Porta()) { 21 | System.out.println("Olá 2"); 22 | } catch (Exception e) { // COMPILA - exceção capturada 23 | } 24 | } 25 | 26 | void try3() throws Exception { // COMPILA - exceção declarada no método 27 | try (Porta porta = new Porta()) { 28 | System.out.println("Olá 3"); 29 | } 30 | } 31 | // end::code[] 32 | } 33 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_CommonTry { 4 | 5 | // tag::code[] 6 | public static void main(String[] args) { 7 | try { 8 | System.out.println("try"); 9 | } // NÃO COMPILA - try "comum" sem catch ou finally 10 | 11 | try { 12 | System.out.println("try"); 13 | } catch (Exception e) { 14 | } // COMPILA - try "comum" só com catch 15 | 16 | try { 17 | System.out.println("try"); 18 | } finally { 19 | } // COMPILA - try "comum" só com finally 20 | 21 | try { 22 | System.out.println("try"); 23 | } catch (Exception e) { 24 | } finally { 25 | } // COMPILA - try "comum" com catch e finally 26 | } 27 | // end::code[] 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.PrintWriter; 6 | 7 | public class TryWithResouces_Java6 { 8 | 9 | // tag::code[] 10 | public static void main(String[] args) throws FileNotFoundException { 11 | File file = new File("arquivo.txt"); 12 | PrintWriter writer = null; 13 | try { 14 | writer = new PrintWriter(file); 15 | writer.println("Olá Mundo!"); 16 | } finally { 17 | if (writer != null) { 18 | writer.close(); // fechando o writer manualmente 19 | } 20 | } 21 | } 22 | // end::code[] 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_NoAutoCloseable { 4 | 5 | // tag::code[] 6 | static class Prateleira {} 7 | 8 | public static void main(String[] args) { 9 | try (Prateleira prateleira = new Prateleira()) { // NÃO COMPILA - Prateleira não implementa AutoClosable 10 | System.out.println("Olá"); 11 | } 12 | } 13 | // end::code[] 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Order.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_Order { 4 | 5 | // tag::code[] 6 | static class Porta implements AutoCloseable { 7 | @Override 8 | public void close() { // chamado automaticamente pelo try-with-resources 9 | System.out.println("Porta fechada."); 10 | } 11 | } 12 | 13 | static class Gaveta implements AutoCloseable { 14 | @Override 15 | public void close() { // chamado automaticamente pelo try-with-resources 16 | System.out.println("Gaveta fechada."); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | try (Porta porta = new Porta(); 22 | Gaveta gaveta = new Gaveta()) { 23 | System.out.println("Olá."); 24 | } 25 | } 26 | // end::code[] 27 | } 28 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_ResourceInsideTry.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_ResourceInsideTry { 4 | 5 | // tag::code[] 6 | static class Porta implements AutoCloseable { 7 | @Override 8 | public void close() { // chamado automaticamente pelo try-with-resources 9 | System.out.println("Porta fechada."); 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | try (Porta porta = new Porta()) { 15 | porta.toString(); 16 | } catch (Exception e) { 17 | porta.toString(); // NÃO COMPILA - variável porta só disponível dentro do bloco try 18 | } finally { 19 | porta.toString(); // NÃO COMPILA - variável porta só disponível dentro do bloco try 20 | } 21 | } 22 | // end::code[] 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Suppressed.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | public class TryWithResouces_Suppressed { 4 | 5 | // tag::code[] 6 | static class Porta implements AutoCloseable { 7 | @Override 8 | public void close() { 9 | System.out.println("close"); 10 | throw new RuntimeException("erro no close"); // lança RuntimeException, mas só depois do try 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | try (Porta porta = new Porta()) { 16 | System.out.println("try"); 17 | throw new RuntimeException("erro no try"); // lança RuntimeException 18 | } catch (RuntimeException e) { // captura RuntimeException - qual foi capturada? 19 | System.out.println(e.getMessage()); // apresenta a mensagem da exceção do try 20 | System.out.println(e.getSuppressed()[0].getMessage()); // apresenta a mensagem da exceção suprimida, ou seja, do close 21 | } 22 | } 23 | // end::code[] 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_WithCatchFinally.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.languageenhancements.trywithresources; 2 | 3 | import java.io.FileNotFoundException; 4 | 5 | public class TryWithResouces_WithCatchFinally { 6 | 7 | // tag::code[] 8 | static class Porta implements AutoCloseable { 9 | @Override 10 | public void close() throws Exception { // chamado automaticamente pelo try-with-resources 11 | System.out.println("Porta fechada."); 12 | throw new Exception(); // lança Exception 13 | } 14 | } 15 | 16 | public static void main(String[] args) throws FileNotFoundException { 17 | try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources 18 | System.out.println("try"); 19 | } catch (Exception e) { 20 | System.out.println("catch"); 21 | } finally { 22 | System.out.println("finally"); 23 | } 24 | } 25 | // end::code[] 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/duration/Duration_Between.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.duration; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalTime; 5 | 6 | public class Duration_Between { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalTime meiaNoite = LocalTime.of(0, 0, 0); 11 | LocalTime meioDia = LocalTime.of (12, 0, 0); 12 | 13 | System.out.println(Duration.between(meiaNoite, meioDia)); 14 | 15 | System.out.println(Duration.between(meioDia, meiaNoite)); 16 | 17 | System.out.println(Duration.between(meioDia, meioDia)); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/duration/Duration_BiggerValues.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.duration; 2 | 3 | import java.time.Duration; 4 | 5 | public class Duration_BiggerValues { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(Duration.ofMinutes(120)); // 120 minutos 10 | System.out.println(Duration.ofMinutes(121)); // 2 horas e 1 minuto 11 | System.out.println(Duration.ofMinutes(119)); // 1 hora e 59 minutos 12 | System.out.println(Duration.ofSeconds(10000)); // 2 horas, 46 minutos e 40 segundos 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/duration/Duration_Compatibility.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.duration; 2 | 3 | import java.time.Duration; 4 | import java.time.Instant; 5 | import java.time.LocalDateTime; 6 | import java.time.LocalTime; 7 | 8 | public class Duration_Compatibility { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | Duration period = Duration.ofHours(2); 13 | System.out.println("Duration: " + period); 14 | 15 | Instant instant = Instant.ofEpochSecond(1558962061L); 16 | System.out.println("\nInstant: " + instant); 17 | System.out.println("Instant + Duration: " + instant.plus(period)); 18 | 19 | LocalTime localTime = LocalTime.of(12, 5, 2); 20 | System.out.println("\nLocalTime: " + localTime); 21 | System.out.println("LocalTime + Duration: " + localTime.plus(period)); 22 | 23 | LocalDateTime localDateTime = LocalDateTime.of(2018, 05, 27, 13, 1, 1); 24 | System.out.println("\nLocalDateTime: " +localDateTime); 25 | System.out.println("LocalDateTime + Duration: " + localDateTime.plus(period)); 26 | // end::code[] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/duration/Duration_LocalDate.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.duration; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalDate; 5 | 6 | public class Duration_LocalDate { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Duration duration = Duration.ofHours(2); 11 | System.out.println("Duration: " + duration); 12 | 13 | LocalDate localDate = LocalDate.of(1990, 8, 6); 14 | System.out.println("LocalTime: " + localDate); 15 | System.out.println("LocalTime + Period: " + localDate.plus(duration)); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/duration/Duration_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.duration; 2 | 3 | import java.time.Duration; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | public class Duration_Of { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | System.out.println(Duration.ofNanos(2)); // 2 nanossegundos 11 | System.out.println(Duration.ofMillis(2)); // 2 milissegundos 12 | System.out.println(Duration.ofSeconds(2)); // 2 segundos 13 | System.out.println(Duration.ofMinutes(2)); // 2 minutos 14 | System.out.println(Duration.ofHours(2)); // 2 horas 15 | System.out.println(Duration.ofDays(2)); // 2 dias (48 horas) 16 | System.out.println(Duration.ofSeconds(2, 200)); // 2,0000002 segundos (2 segundos e 200 nanossegundos) 17 | System.out.println(Duration.of(2, ChronoUnit.MICROS)); // 2 microssegundos 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/instant/Instant_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.instant; 2 | 3 | import java.time.Instant; 4 | 5 | public class Instant_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Instant instant = new Instant(); // NÃO COMPILA! - não possui construtor padrão 10 | System.out.println(instant); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/instant/Instant_Convert.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.instant; 2 | 3 | import java.time.Instant; 4 | import java.time.LocalDateTime; 5 | import java.time.ZoneOffset; 6 | 7 | public class Instant_Convert { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | LocalDateTime localDateTime = LocalDateTime.of(2019, 5, 27, 13, 1, 1); 12 | System.out.println("LocalDateTime: " + localDateTime); 13 | System.out.println(localDateTime.toInstant(ZoneOffset.UTC)); 14 | System.out.println(localDateTime.toInstant(ZoneOffset.of("-3"))); 15 | 16 | Instant instant = Instant.ofEpochSecond(1558962061L); // mesma data do localDateTime 17 | System.out.println("\nInstant: " + instant); 18 | System.out.println(LocalDateTime.ofInstant(instant, ZoneOffset.UTC)); 19 | System.out.println(LocalDateTime.ofInstant(instant, ZoneOffset.of("-3"))); 20 | // end::code[] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/instant/Instant_Immutability.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.instant; 2 | 3 | import java.time.Instant; 4 | 5 | public class Instant_Immutability { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Instant instant = Instant.ofEpochMilli(1000000000000L); 10 | System.out.println(instant); 11 | instant.plusSeconds(60); // chamada perdida - a nova data/hora não foi armazenada em uma variável 12 | System.out.println(instant); 13 | instant = instant.plusSeconds(60); // chamada útil - data/hora armazenada na variável 14 | System.out.println(instant); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/instant/Instant_Now.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.instant; 2 | 3 | import java.time.Instant; 4 | 5 | public class Instant_Now { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(Instant.now()); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/instant/Instant_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.instant; 2 | 3 | import java.time.Instant; 4 | 5 | public class Instant_Of { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(Instant.ofEpochMilli(1000000000000L)); 10 | System.out.println(Instant.ofEpochSecond(1000000000)); 11 | System.out.println(Instant.ofEpochSecond(1000000000, 123000000)); // com nanossegundos 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_AdjustDifferentUnit.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | public class LocalDate_AdjustDifferentUnit { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDate localDate = LocalDate.of(2019, Month.NOVEMBER, 30); 11 | System.out.println(localDate); 12 | System.out.println(localDate.plusDays(1)); // + 1 dia, vira o mês 13 | System.out.println(localDate.plusDays(32)); // + 32 dias, vira o ano 14 | System.out.println(localDate.plusMonths(2)); // + 2 meses, vira o ano 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Chaining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | public class LocalDate_Chaining { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDate localDate = LocalDate.of(2019, Month.MAY, 20); 11 | System.out.println(localDate); 12 | System.out.println(localDate.plusDays(1).plusMonths(1).plusYears(1)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class LocalDate_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalDate localDate = new LocalDate(); // NÃO COMPILA! - não possui construtor padrão 10 | System.out.println(localDate); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Immutability.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | public class LocalDate_Immutability { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDate localDate = LocalDate.of(2019, Month.MAY, 20); 11 | System.out.println(localDate); 12 | localDate.plusDays(1); // chamada perdida - a nova data não foi armazenada em uma variável 13 | System.out.println(localDate); 14 | localDate = localDate.plusDays(1); // chamada útil - data armazenada na variável 15 | System.out.println(localDate); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Invalid.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | public class LocalDate_Invalid { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | System.out.println(LocalDate.of(2019, Month.MAY, 33)); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Now.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class LocalDate_Now { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalDate.now()); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdate/LocalDate_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdate; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | public class LocalDate_Of { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | System.out.println(LocalDate.of(2019, 5, 20)); 11 | System.out.println(LocalDate.of(2019, Month.MAY, 20)); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_AdjustDifferentUnit.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class LocalDateTime_AdjustDifferentUnit { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalDateTime localDateTime = LocalDateTime.of(2019, 12, 31, 23, 59, 59); 10 | System.out.println(localDateTime); 11 | System.out.println(localDateTime.plusSeconds(2)); // + 2 segundos, vira o ano 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Chaining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class LocalDateTime_Chaining { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalDateTime localDateTime = LocalDateTime.of(2019, 5, 20, 9, 20); 10 | System.out.println(localDateTime); 11 | System.out.println(localDateTime.plusDays(1).plusHours(1).plusYears(1)); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class LocalDateTime_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalDateTime localDateTime = new LocalDateTime(); // NÃO COMPILA! - não possui construtor padrão 10 | System.out.println(localDateTime); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Immutability.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class LocalDateTime_Immutability { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalDateTime localDateTime = LocalDateTime.of(2019, 5, 20, 9, 20); 10 | System.out.println(localDateTime); 11 | localDateTime.plusHours(1); // chamada perdida - a nova data/hora não foi armazenada em uma variável 12 | System.out.println(localDateTime); 13 | localDateTime = localDateTime.plusHours(1); // chamada útil - data/hora armazenada na variável 14 | System.out.println(localDateTime); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Invalid.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class LocalDateTime_Invalid { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalDateTime.of(2019, 4, 31, 9, 20)); // lança exceção: não existe 31 de abril 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Now.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class LocalDateTime_Now { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalDateTime.now()); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localdatetime/LocalDateTime_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localdatetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.Month; 7 | 8 | public class LocalDateTime_Of { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | System.out.println(LocalDateTime.of(LocalDate.of(2019, 5, 20), LocalTime.of(9, 20, 12))); 13 | System.out.println(LocalDateTime.of(2019, 5, 20, 9, 20)); 14 | System.out.println(LocalDateTime.of(2019, Month.MAY, 20, 9, 20)); 15 | System.out.println(LocalDateTime.of(2019, 5, 20, 9, 20, 12)); 16 | System.out.println(LocalDateTime.of(2019, Month.MAY, 20, 9, 20, 12)); 17 | System.out.println(LocalDateTime.of(2019, 5, 20, 9, 20, 12, 135)); 18 | System.out.println(LocalDateTime.of(2019, Month.MAY, 20, 9, 20, 12, 135)); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_AdjustDifferentUnit.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_AdjustDifferentUnit { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalTime localTime = LocalTime.of(9, 59, 59); 10 | System.out.println(localTime); 11 | System.out.println(localTime.plusSeconds(2)); // + 2 segundos, vira o minuto 12 | System.out.println(localTime.plusSeconds(62)); // + 62 segundos, vira a hora 13 | System.out.println(localTime.plusMinutes(2)); // + 2 minutos, vira a hora 14 | System.out.println(localTime.minusNanos(1000000000)); // - 1 segundo (em nanos), vira o minuto 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Chaining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_Chaining { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalTime localTime = LocalTime.of(9, 32, 5); 10 | System.out.println(localTime); 11 | System.out.println(localTime.plusHours(1).plusMinutes(1).plusSeconds(1).plusNanos(1000000)); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class LocalTime_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalTime localTime = new LocalTime(); // NÃO COMPILA! - não possui construtor padrão 10 | System.out.println(localTime); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Immutability.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_Immutability { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | LocalTime localTime = LocalTime.of(9, 31, 5); 10 | System.out.println(localTime); 11 | localTime.plusHours(1); // chamada perdida - a nova hora não foi armazenada em uma variável 12 | System.out.println(localTime); 13 | localTime = localTime.plusHours(1); // chamada útil - hora armazenada na variável 14 | System.out.println(localTime); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Invalid.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_Invalid { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalTime.of(24, 2, 3)); // lança exceção: a hora deve estar entre 0 e 23 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Now.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_Now { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalTime.now()); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/localtime/LocalTime_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.localtime; 2 | 3 | import java.time.LocalTime; 4 | 5 | public class LocalTime_Of { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(LocalTime.of(9, 20, 1, 135000000)); 10 | System.out.println(LocalTime.of(9, 20, 1, 135)); 11 | System.out.println(LocalTime.of(9, 20, 1)); 12 | System.out.println(LocalTime.of(9, 20)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_Between.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | 6 | public class Period_Between { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDate nascimento = LocalDate.of(1990, 8, 6); 11 | LocalDate hoje = LocalDate.now(); 12 | Period idade = Period.between(nascimento, hoje); 13 | System.out.println(idade); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_BiggerValues.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.Period; 4 | 5 | public class Period_BiggerValues { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(Period.of(0, 60, 2)); // 60 meses e 2 dias 10 | System.out.println(Period.of(0, 30, 50)); // 30 meses e 50 dias 11 | System.out.println(Period.of(5, 200, 1000)); // 5 anos, 200 meses e 1000 dias 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_Compatibility.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.Instant; 4 | import java.time.LocalDate; 5 | import java.time.LocalDateTime; 6 | import java.time.Period; 7 | 8 | public class Period_Compatibility { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | Period period = Period.ofDays(10); 13 | System.out.println("Period: " + period); 14 | 15 | Instant instant = Instant.ofEpochSecond(1558962061L); 16 | System.out.println("\nInstant: " + instant); 17 | System.out.println("Instant + Period: " + instant.plus(period)); 18 | 19 | LocalDate localDate = LocalDate.of(2018, 5, 27); 20 | System.out.println("\nLocalDate: " + localDate); 21 | System.out.println("LocalDate + Period: " + localDate.plus(period)); 22 | 23 | LocalDateTime localDateTime = LocalDateTime.of(2018, 05, 27, 13, 1, 1); 24 | System.out.println("\nLocalDateTime: " +localDateTime); 25 | System.out.println("LocalDateTime + Period: " + localDateTime.plus(period)); 26 | // end::code[] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_Curiosities.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.Instant; 4 | import java.time.Period; 5 | 6 | public class Period_Curiosities { 7 | 8 | public static void main(String[] args) { 9 | 10 | // tag::code1[] 11 | System.out.println(Period.of(0, 60, 2)); // P60M2D 12 | System.out.println(Period.of(0, 60, 2).normalized()); // P5Y2D 13 | 14 | System.out.println(Period.of(0, 30, 50)); // P30M50D 15 | System.out.println(Period.of(0, 30, 50).normalized()); // P2Y6M50D 16 | // end::code1[] 17 | 18 | // tag::code2[] 19 | System.out.println(Period.of(1, -25, 0)); // P1Y-25M 20 | System.out.println(Period.of(1, -25, 0).normalized()); // P-1Y-1M 21 | // end::code2[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_Instant.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.Instant; 4 | import java.time.Period; 5 | 6 | public class Period_Instant { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Period period = Period.ofMonths(1); 11 | System.out.println("Period: " + period); 12 | 13 | Instant instant = Instant.ofEpochSecond(1558962061L); 14 | System.out.println("Instant: " + instant); 15 | System.out.println("Instant + Period: " + instant.plus(period)); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_LocalTime.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.LocalTime; 4 | import java.time.Period; 5 | 6 | public class Period_LocalTime { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Period period = Period.ofDays(13); 11 | System.out.println("Period: " + period); 12 | 13 | LocalTime localTime = LocalTime.of(13, 1, 1); 14 | System.out.println("LocalTime: " + localTime); 15 | System.out.println("LocalTime + Period: " + localTime.plus(period)); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/datetime/period/Period_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.datetime.period; 2 | 3 | import java.time.Period; 4 | 5 | public class Period_Of { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(Period.ofDays(2)); // período de 2 dias 10 | System.out.println(Period.ofMonths(2)); // período de 2 meses 11 | System.out.println(Period.ofWeeks(2)); // período de 2 semanas 12 | System.out.println(Period.ofYears(2)); // período de 2 anos 13 | System.out.println(Period.of(2, 1, 3)); // 2 anos, 1 mês e 3 dias 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/dateformat/DateFormat_Parse.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.dateformat; 2 | 3 | import java.text.DateFormat; 4 | import java.text.ParseException; 5 | 6 | public class DateFormat_Parse { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | DateFormat dateInstance = DateFormat.getDateInstance(DateFormat.SHORT); 11 | DateFormat timeInstance = DateFormat.getTimeInstance(DateFormat.SHORT); 12 | DateFormat dateTimeInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); 13 | 14 | String date = "08/09/2001"; 15 | String time = "22:46:40"; 16 | String dateTime = "08/09/2001 22:46:40"; 17 | 18 | try { 19 | System.out.println(dateInstance.parse(date)); 20 | System.out.println(timeInstance.parse(time)); 21 | System.out.println(dateTimeInstance.parse(dateTime)); 22 | System.out.println(dateTimeInstance.parse(date)); // exceção, pois date não tem hora 23 | } catch (ParseException e) { 24 | System.out.println(e.getMessage()); 25 | } 26 | // end::code[] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Custom.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class DateTimeFormatter_Custom { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDateTime localDT = LocalDateTime.of(2019, 8, 6, 11, 40); 11 | 12 | DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd MM yy - HH mm ss"); 13 | 14 | System.out.println(localDT.format(customFormatter)); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Error.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.format.DateTimeFormatter; 7 | 8 | public class DateTimeFormatter_Error { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | LocalDate localDate = LocalDate.of(2019, 8, 6); 13 | LocalTime localTime = LocalTime.of(11, 40); 14 | LocalDateTime localDT = LocalDateTime.of(localDate, localTime); 15 | 16 | System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE)); 17 | System.out.println(localDT.format(DateTimeFormatter.ISO_LOCAL_DATE)); 18 | 19 | // lança exceção pois não possui campos de data 20 | System.out.println(localTime.format(DateTimeFormatter.ISO_LOCAL_DATE)); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_ErrorCustom.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.format.DateTimeFormatter; 7 | 8 | public class DateTimeFormatter_ErrorCustom { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | LocalDate localDate = LocalDate.of(2019, 8, 6); 13 | LocalTime localTime = LocalTime.of(11, 40); 14 | LocalDateTime localDT = LocalDateTime.of(localDate, localTime); 15 | 16 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH mm ss"); 17 | 18 | System.out.println(localDT.format(formatter)); 19 | System.out.println(localTime.format(formatter)); 20 | System.out.println(localDate.format(formatter)); // lança exceção pois não possui campos de hora 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Inverted.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | import java.time.temporal.TemporalAccessor; 6 | 7 | public class DateTimeFormatter_Inverted { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | LocalDateTime localDT = LocalDateTime.of(2019, 8, 6, 11, 40); 12 | System.out.println(localDT); 13 | 14 | String format = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDT); 15 | System.out.println(format); 16 | 17 | TemporalAccessor parse = DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(format); 18 | System.out.println(parse); 19 | System.out.println(LocalDateTime.from(parse)); 20 | // end::code[] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Locale.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | import java.time.format.FormatStyle; 6 | import java.util.Locale; 7 | 8 | public class DateTimeFormatter_Locale { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | LocalDateTime localDT = LocalDateTime.of(2019, 8, 6, 11, 40); 13 | 14 | DateTimeFormatter shortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT); 15 | DateTimeFormatter mediumFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); 16 | 17 | shortFormatter = shortFormatter.withLocale(Locale.US); 18 | mediumFormatter = mediumFormatter.withLocale(Locale.US); 19 | 20 | System.out.println(localDT.format(shortFormatter)); 21 | System.out.println(localDT.format(mediumFormatter)); 22 | // end::code[] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Parse.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | import java.time.format.FormatStyle; 6 | 7 | public class DateTimeFormatter_Parse { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd MM yy - HH mm ss"); 12 | DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; 13 | DateTimeFormatter shortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT); 14 | 15 | LocalDateTime parseCustom = LocalDateTime.parse("06 08 19 - 11 40 00", customFormatter); 16 | LocalDateTime parseIso = LocalDateTime.parse("2019-08-06T11:40:00", isoFormatter); 17 | LocalDateTime parseShort = LocalDateTime.parse("06/08/19 11:40", shortFormatter); 18 | 19 | System.out.println(parseCustom); 20 | System.out.println(parseIso); 21 | System.out.println(parseShort); 22 | // end::code[] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/datetimeformatter/DateTimeFormatter_Predefined.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.datetimeformatter; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class DateTimeFormatter_Predefined { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | LocalDateTime localDT = LocalDateTime.of(2019, 8, 6, 11, 40); 11 | System.out.println(localDT.format(DateTimeFormatter.ISO_LOCAL_DATE)); 12 | System.out.println(localDT.format(DateTimeFormatter.ISO_LOCAL_TIME)); 13 | System.out.println(localDT.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 14 | System.out.println(localDT.format(DateTimeFormatter.ISO_ORDINAL_DATE)); 15 | System.out.println(localDT.format(DateTimeFormatter.ISO_WEEK_DATE)); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Locale.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.decimalformat; 2 | 3 | import java.text.DecimalFormat; 4 | import java.text.NumberFormat; 5 | import java.util.Locale; 6 | 7 | public class DecimalFormat_Locale { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | double d = 12345.67; 12 | 13 | NumberFormat numberFormatUS = NumberFormat.getNumberInstance(Locale.US); 14 | DecimalFormat decimalFormatUS = (DecimalFormat) numberFormatUS; 15 | decimalFormatUS.applyLocalizedPattern("###,###.###"); 16 | System.out.println(decimalFormatUS.format(d)); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/decimalformat/DecimalFormat_Strings.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.decimalformat; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | public class DecimalFormat_Strings { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | double d = 12345.67; 10 | 11 | DecimalFormat decimalFormat = new DecimalFormat("Número ###,###.### formatado"); 12 | System.out.println(decimalFormat.format(d)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/numberformat/NumberFormat_Instance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.numberformat; 2 | 3 | import java.text.NumberFormat; 4 | import java.util.Locale; 5 | 6 | public class NumberFormat_Instance { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | // sem Locale 11 | NumberFormat instance1 = NumberFormat.getInstance(); 12 | NumberFormat instance2 = NumberFormat.getNumberInstance(); // igual a getInstance() 13 | NumberFormat instance3 = NumberFormat.getCurrencyInstance(); 14 | NumberFormat instance4 = NumberFormat.getPercentInstance(); 15 | 16 | // com Locale 17 | NumberFormat instance5 = NumberFormat.getInstance(new Locale("pt", "BR")); 18 | NumberFormat instance6 = NumberFormat.getNumberInstance(new Locale("pt", "BR")); 19 | NumberFormat instance7 = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); 20 | NumberFormat instance8 = NumberFormat.getPercentInstance(new Locale("pt", "BR")); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/numberformat/NumberFormat_NumberToString.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.numberformat; 2 | 3 | import java.text.NumberFormat; 4 | import java.util.Locale; 5 | 6 | public class NumberFormat_NumberToString { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | NumberFormat numberFormatPtBR = NumberFormat.getInstance(new Locale("pt", "BR")); 11 | NumberFormat numberFormatEnUS = NumberFormat.getInstance(new Locale("en", "US")); 12 | NumberFormat numberFormatFrFR = NumberFormat.getInstance(new Locale("fr", "FR")); 13 | 14 | double d = 1000.05; 15 | 16 | System.out.println("pt_BR: " + numberFormatPtBR.format(d)); 17 | System.out.println("en_US: " + numberFormatEnUS.format(d)); 18 | System.out.println("fr_FR: " + numberFormatFrFR.format(d)); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/numberformat/NumberFormat_Percent2.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.numberformat; 2 | 3 | import java.text.NumberFormat; 4 | import java.text.ParseException; 5 | import java.util.Locale; 6 | 7 | public class NumberFormat_Percent2 { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | NumberFormat percentFormatPtBR = NumberFormat.getPercentInstance(new Locale("pt", "BR")); 12 | NumberFormat percentFormatEnUS = NumberFormat.getPercentInstance(new Locale("en", "US")); 13 | 14 | // String para Percentual 15 | String s = "80,2%"; 16 | 17 | try { 18 | System.out.println("pt_BR: " + percentFormatPtBR.parse(s)); 19 | System.out.println("en_US: " + percentFormatEnUS.parse(s)); 20 | } catch (ParseException e) { 21 | // trate a exceção de parse 22 | } 23 | // end::code[] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/numberformat/NumberFormat_StringToNumber.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.numberformat; 2 | 3 | import java.text.NumberFormat; 4 | import java.text.ParseException; 5 | import java.util.Locale; 6 | 7 | public class NumberFormat_StringToNumber { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | NumberFormat numberFormatPtBR = NumberFormat.getInstance(new Locale("pt", "BR")); 12 | NumberFormat numberFormatEnUS = NumberFormat.getInstance(new Locale("en", "US")); 13 | NumberFormat numberFormatFrFR = NumberFormat.getInstance(new Locale("fr", "FR")); 14 | 15 | String s = "1000,05"; 16 | 17 | try { 18 | Number parsePtBR = numberFormatPtBR.parse(s); 19 | Number parseEnUS = numberFormatEnUS.parse(s); 20 | Number parseFrFR = numberFormatFrFR.parse(s); 21 | 22 | System.out.println("pt_BR: " + parsePtBR); 23 | System.out.println("en_US: " + parseEnUS); 24 | System.out.println("fr_FR: " + parseFrFR); 25 | } catch (ParseException e) { 26 | // trate a exceção no parse 27 | } 28 | // end::code[] 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Instance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.simpledateformat; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | public class SimpleDateFormat_Instance { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | SimpleDateFormat simpleDateTime = new SimpleDateFormat("dd MM yy - HH mm ss"); 11 | SimpleDateFormat simpleDate = new SimpleDateFormat("dd MM yy"); 12 | SimpleDateFormat simpleTime = new SimpleDateFormat("HH mm ss"); 13 | 14 | Date date = new Date(1000000000000L); // data em quantidade de milissegundos desde 01/01/1970 15 | 16 | System.out.println(simpleDateTime.format(date)); 17 | System.out.println(simpleDate.format(date)); 18 | System.out.println(simpleTime.format(date)); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/formats/simpledateformat/SimpleDateFormat_Parse.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.formats.simpledateformat; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | 6 | public class SimpleDateFormat_Parse { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | SimpleDateFormat simpleDateTime = new SimpleDateFormat("dd MM yy - HH mm ss"); 11 | SimpleDateFormat simpleDate = new SimpleDateFormat("dd MM yy"); 12 | SimpleDateFormat simpleTime = new SimpleDateFormat("HH mm ss"); 13 | 14 | String dateTime = "08 09 01 - 22 46 40"; 15 | String date = "08 09 01"; 16 | String time = "22 46 40"; 17 | 18 | try { 19 | System.out.println(simpleDateTime.parse(dateTime)); 20 | System.out.println(simpleDate.parse(date)); 21 | System.out.println(simpleTime.parse(time)); 22 | System.out.println(simpleDateTime.parse(time)); // exceção, pois time não tem data 23 | } catch (ParseException e) { 24 | System.out.println(e.getMessage()); 25 | } 26 | // end::code[] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleAvailable.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleAvailable { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | Locale[] availableLocales = Locale.getAvailableLocales(); 11 | // imprime o 10 primeiros Locales disponíveis 12 | for (int i = 0; i < 10; i++) { 13 | System.out.println(availableLocales[i]); 14 | } 15 | } 16 | // end::code[] 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleCase.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleCase { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | System.out.println(new Locale("PT", "br")); 11 | 12 | System.out.println(Locale.forLanguageTag("PT-br")); 13 | 14 | Locale localePtBR = new Locale.Builder() 15 | .setLanguage("PT") 16 | .setRegion("br") 17 | .build(); 18 | 19 | System.out.println(localePtBR); 20 | } 21 | // end::code[] 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleCommons.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleCommons { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | System.out.println(Locale.CANADA); 11 | System.out.println(Locale.CANADA_FRENCH); 12 | System.out.println(Locale.CHINA); 13 | System.out.println(Locale.CHINESE); 14 | System.out.println(Locale.ENGLISH); 15 | System.out.println(Locale.ITALY); 16 | System.out.println(Locale.SIMPLIFIED_CHINESE); 17 | System.out.println(Locale.TRADITIONAL_CHINESE); 18 | } 19 | // end::code[] 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleDefault.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleDefault { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | System.out.println(Locale.getDefault()); // o padrão inicial muda de acordo com seu dispositivo 11 | Locale.setDefault(Locale.KOREA); // altera o Locale default 12 | System.out.println(Locale.getDefault()); // ko_KR 13 | } 14 | // end::code[] 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleInstantiation.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleInstantiation { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | new Locale("pt", "BR"); // pt-BR com Construtor 11 | 12 | Locale.forLanguageTag("pt-BR"); // pt-BR com LanguageTag 13 | 14 | Locale localePtBR = new Locale.Builder() // pt-BR com Builder 15 | .setLanguage("pt") 16 | .setRegion("BR") 17 | .build(); 18 | } 19 | // end::code[] 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleLanguageCountry.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleLanguageCountry { 7 | 8 | public static void main(String[] args) throws IOException { 9 | // tag::code[] 10 | new Locale("pt", "BR"); // Português do Brasil 11 | new Locale("en", "US"); // Inglês dos EUA 12 | new Locale("it", "CH"); // Italiano da Suíça 13 | new Locale("fr", "BE"); // Francês da Bélgica 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_LocaleLanguageOnly.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_LocaleLanguageOnly { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | System.out.println(new Locale("pt")); // português 11 | System.out.println(new Locale("en")); // inglês 12 | System.out.println(new Locale("es")); // espanhol 13 | System.out.println(new Locale("fr")); // francês 14 | } 15 | // end::code[] 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/locale/Locale_VarScriptExtension.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.locale; 2 | 3 | import java.io.IOException; 4 | import java.util.Locale; 5 | 6 | public class Locale_VarScriptExtension { 7 | 8 | // tag::code[] 9 | public static void main(String[] args) throws IOException { 10 | Locale locale2 = new Locale.Builder() // az_AZ_#Latn 11 | .setLanguage("az") 12 | .setRegion("AZ") 13 | .setScript("Latn") 14 | .build(); 15 | 16 | Locale locale3 = new Locale.Builder() // bs_BA_POSIX_#Latn_c-cc 17 | .setLanguage("bs") 18 | .setRegion("BA") 19 | .setVariant("POSIX") 20 | .setScript("Latn") 21 | .setExtension('c', "cc") 22 | .build(); 23 | } 24 | // end::code[] 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/resourcebundle/ResourceBundle_Inheritance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.resourcebundle; 2 | 3 | import java.util.Locale; 4 | import java.util.ResourceBundle; 5 | 6 | public class ResourceBundle_Inheritance { 7 | 8 | public static void main(String[] args) { 9 | 10 | // tag::code[] 11 | Locale.setDefault(new Locale("en", "US")); // pt_BR como Locale padrão 12 | ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("pt", "BR")); 13 | System.out.println("Locale: " + bundle.getLocale()); // Bundle localizado para o Locale "pt_BR" (Português do Brasil) 14 | System.out.println(bundle.getObject("pen")); 15 | System.out.println(bundle.getObject("paper")); 16 | System.out.println(bundle.getObject("keyboard")); 17 | // end::code[] 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaBundle.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.resourcebundle; 2 | 3 | import java.util.Locale; 4 | import java.util.ResourceBundle; 5 | 6 | public class ResourceBundle_JavaBundle { 7 | 8 | public static void main(String[] args) { 9 | 10 | // tag::code[] 11 | ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("fr", "CA")); 12 | System.out.println(bundle.getString("glass")); 13 | // end::code[] 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/resourcebundle/ResourceBundle_JavaClassTakesPrecedence.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.resourcebundle; 2 | 3 | import java.util.Locale; 4 | import java.util.ResourceBundle; 5 | 6 | public class ResourceBundle_JavaClassTakesPrecedence { 7 | 8 | public static void main(String[] args) { 9 | 10 | // tag::code[] 11 | /* 12 | * Recupera o Bundle do arquivo "Text_fr_CA.java", 13 | * pois tem precedência sobre o arquivo "Text_fr_CA.properties" 14 | */ 15 | ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("fr", "CA")); 16 | System.out.println(bundle.getString("pen")); 17 | System.out.println(bundle.getString("glass")); 18 | System.out.println(bundle.getString("keyboard")); 19 | // end::code[] 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/resourcebundle/ResourceBundle_KeysProgrammatically.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.resourcebundle; 2 | 3 | import java.util.Locale; 4 | import java.util.ResourceBundle; 5 | import java.util.Set; 6 | 7 | public class ResourceBundle_KeysProgrammatically { 8 | 9 | // tag::code[] 10 | public static void main(String[] args) { 11 | 12 | Locale.setDefault(new Locale("en", "US")); // Coloca o Locale en_US como padrão 13 | 14 | ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("pt", "BR")); // Recupera o bundle 'Text' para o Locale pt_BR 15 | Set keySet = bundle.keySet(); // Pega um Set com todas as chaves 16 | for (String key : keySet) { 17 | System.out.println(key + " - " + bundle.getString(key)); // Imprime " - " 18 | } 19 | 20 | } 21 | // end::code[] 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/resourcebundle/ResourceBundle_NotExactLocale.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.resourcebundle; 2 | 3 | import java.util.Locale; 4 | import java.util.ResourceBundle; 5 | 6 | public class ResourceBundle_NotExactLocale { 7 | 8 | public static void main(String[] args) { 9 | 10 | // tag::code[] 11 | Locale.setDefault(new Locale("pt", "BR")); // pt_BR como Locale padrão 12 | ResourceBundle bundle2 = ResourceBundle.getBundle("Text", new Locale("zh", "CN")); 13 | System.out.println(bundle2.getLocale()); // Bundle localizado para o Locale "zh_CH" (Chinês simplificado) 14 | ResourceBundle bundle = ResourceBundle.getBundle("Text", new Locale("it", "CH")); 15 | System.out.println(bundle.getLocale()); // Bundle localizado para o Locale "it_CH" (Italiano da Suíça) 16 | // end::code[] 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Chaining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZonedDateTime; 5 | 6 | public class ZonedDateTime_Chaining { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ZonedDateTime zonedDateTime = ZonedDateTime.of(2019, 5, 20, 9, 20, 4, 300, ZoneId.of("America/Sao_Paulo")); 11 | System.out.println(zonedDateTime); 12 | System.out.println(zonedDateTime.plusDays(1).plusHours(1).plusYears(1)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Constructor.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZonedDateTime; 4 | 5 | public class ZonedDateTime_Constructor { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | ZonedDateTime zonedDateTime = new ZonedDateTime(); // NÃO COMPILA! - não possui construtor público 10 | System.out.println(zonedDateTime); 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_DaylightSavings.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZonedDateTime; 5 | 6 | public class ZonedDateTime_DaylightSavings { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ZonedDateTime zonedDateTime = ZonedDateTime.of(2018, 11, 3, 23, 30, 0, 0, ZoneId.of("America/Sao_Paulo")); 11 | System.out.println(zonedDateTime); 12 | System.out.println("+2 horas: " + zonedDateTime.plusHours(2)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Immutability.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZonedDateTime; 5 | 6 | public class ZonedDateTime_Immutability { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ZonedDateTime zonedDateTime = ZonedDateTime.of(2019, 5, 20, 9, 20, 3, 300, ZoneId.of("America/Sao_Paulo")); 11 | System.out.println(zonedDateTime); 12 | zonedDateTime.plusHours(1); // chamada perdida - a nova data/hora não foi armazenada em uma variável 13 | System.out.println(zonedDateTime); 14 | zonedDateTime = zonedDateTime.plusHours(1); // chamada útil - data/hora armazenada na variável 15 | System.out.println(zonedDateTime); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Invalid.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZonedDateTime; 5 | 6 | public class ZonedDateTime_Invalid { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | 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 11 | // end::code[] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Now.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZonedDateTime; 4 | 5 | public class ZonedDateTime_Now { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | System.out.println(ZonedDateTime.now()); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.ZoneId; 7 | import java.time.ZonedDateTime; 8 | 9 | public class ZonedDateTime_Of { 10 | 11 | public static void main(String[] args) { 12 | // tag::code[] 13 | System.out.println(ZonedDateTime.of(2019, 6, 9, 13, 20, 3, 1000, ZoneId.of("America/Sao_Paulo"))); 14 | 15 | LocalDateTime localDateTime = LocalDateTime.of(2019, 6, 9, 13, 20, 3, 1000); 16 | System.out.println(ZonedDateTime.of(localDateTime, ZoneId.of("America/Sao_Paulo"))); 17 | 18 | LocalDate localDate = LocalDate.of(2019, 6, 9); 19 | LocalTime localTime = LocalTime.of(13, 20, 3, 1000); 20 | System.out.println(ZonedDateTime.of(localDate, localTime, ZoneId.of("America/Sao_Paulo"))); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/localization/timezones/ZonedDateTime_Zones.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.localization.timezones; 2 | 3 | import java.time.ZoneId; 4 | import java.util.Set; 5 | 6 | public class ZonedDateTime_Zones { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Set availableZoneIds = ZoneId.getAvailableZoneIds(); 11 | for (String zoneId : availableZoneIds) { 12 | System.out.println(zoneId); 13 | } 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_Parallel.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Streams_Parallel { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | String[] array = new String[] { "A", "B", "C" }; 10 | Arrays.stream(array) 11 | .parallel() // stream transformado em paralelo 12 | .forEach(System.out::println); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelFindAny.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Optional; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_ParallelFindAny { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Optional findAny1 = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) 11 | .findFirst(); 12 | System.out.println("findAny Sequencial: " + findAny1.get()); 13 | 14 | Optional findAny2 = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) 15 | .parallel() 16 | .findAny(); 17 | System.out.println("findAny Paralelo: " + findAny2.get()); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEach.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Streams_ParallelForEach { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList("A", "B", "C"); 11 | 12 | System.out.println("Sequencial: "); 13 | list.stream() // cria um Stream sequencial 14 | .forEach(System.out::println); 15 | 16 | System.out.println("Paralelo: "); 17 | list.parallelStream() // cria um Stream paralelo 18 | .forEach(System.out::println); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelForEachOrdered.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Streams_ParallelForEachOrdered { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList("A", "B", "C"); 11 | 12 | System.out.println("Sequencial: "); 13 | list.stream() // cria um Stream sequencial 14 | .forEachOrdered(System.out::println); 15 | 16 | System.out.println("Paralelo: "); 17 | list.parallelStream() // cria um Stream paralelo 18 | .forEachOrdered(System.out::println); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelGroupingByConcurrent.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class Streams_ParallelGroupingByConcurrent { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | Map> collect1 = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 13 | .parallel() 14 | .collect(Collectors.groupingBy(s -> s.length())); 15 | System.out.println(collect1); 16 | 17 | Map> collect2 = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 18 | .parallel() 19 | .collect(Collectors.groupingByConcurrent(s -> s.length())); 20 | System.out.println(collect2); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelPerformance.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_ParallelPerformance { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | long inicio = System.currentTimeMillis(); 10 | IntStream.range(0, Integer.MAX_VALUE) // stream sequencial 11 | .mapToDouble(n -> Math.pow(n, 2)) 12 | .average() 13 | .ifPresent(n -> System.out.println("Tempo stream sequencial: " + (System.currentTimeMillis() - inicio))); 14 | 15 | long inicio2 = System.currentTimeMillis(); 16 | IntStream.range(0, Integer.MAX_VALUE) 17 | .parallel() // stream paralelo 18 | .mapToDouble(n -> Math.pow(n, 2)) 19 | .average() 20 | .ifPresent(n -> System.out.println("Tempo stream paralelo: " + (System.currentTimeMillis() - inicio2))); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelReduceAssociative.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_ParallelReduceAssociative { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Stream.of(7, 2, 3, 8, 2, 1, 4, 5) 10 | .reduce((e1, e2) -> e1 * e2) 11 | .ifPresent(System.out::println); 12 | 13 | Stream.of(7, 2, 3, 8, 2, 1, 4, 5) 14 | .parallel() 15 | .reduce((e1, e2) -> e1 * e2) 16 | .ifPresent(System.out::println); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelReduceNonAssociative.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_ParallelReduceNonAssociative { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Stream.of(7, 2, 3, 8, 2, 1, 4, 5) 10 | .reduce((e1, e2) -> e1 - e2) 11 | .ifPresent(System.out::println); 12 | 13 | Stream.of(7, 2, 3, 8, 2, 1, 4, 5) 14 | .parallel() 15 | .reduce((e1, e2) -> e1 - e2) 16 | .ifPresent(System.out::println); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelStatefulOperation.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | public class Streams_ParallelStatefulOperation { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | List synchronizedList = Collections.synchronizedList(new ArrayList<>()); 13 | List list = Arrays.asList("A", "B", "C"); 14 | 15 | System.out.println("Ordem no forEachOrdered: "); 16 | list.parallelStream() 17 | .map(s -> {synchronizedList.add(s); return s;}) // operação com efeito colateral - altera o estado de um objeto 18 | .forEachOrdered(System.out::println); 19 | 20 | System.out.println("Ordem na synchronizedList: "); 21 | for (String s : synchronizedList) { 22 | System.out.println(s); 23 | } 24 | // end::code[] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelStream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Streams_ParallelStream { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList("A", "B", "C"); 11 | list.parallelStream() // cria um Stream paralelo diretamente 12 | .forEach(System.out::println); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/parallelstreams/Streams_ParallelToConcurrentMap.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.parallelstreams; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_ParallelToConcurrentMap { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | Map collect1 = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 12 | .parallel() 13 | .collect(Collectors.toMap(s -> s, s -> s.length())); 14 | System.out.println("toMap: " + collect1); 15 | 16 | Map collect2 = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 17 | .parallel() 18 | .collect(Collectors.toConcurrentMap(s -> s, s -> s.length())); 19 | System.out.println("toConcurrentMap: " + collect2); 20 | // end::code[] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_ArraysStream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Streams_ArraysStream { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // Criação de um array comum de Strings 10 | String[] array = new String[] { "A", "B", "C" }; 11 | // Criação de um Stream a partir do array e, para 12 | // cada elemento, o método println é chamado. 13 | Arrays.stream(array).forEach(System.out::println); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_ChangeBackingList.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.ArrayList; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_ChangeBackingList { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | ArrayList list = new ArrayList(); 11 | list.add(1); 12 | list.add(2); 13 | list.add(3); 14 | 15 | Stream stream = list.stream(); 16 | 17 | list.add(4); 18 | 19 | stream.forEach(System.out::println); 20 | // end::code[] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Distinct.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Streams_Distinct { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // Criação de um array comum de Strings 10 | String[] array = new String[] { "A", "B", "C", "A", "B", "F" }; 11 | 12 | Arrays.stream(array) 13 | .distinct() // ignora elementos repetidos 14 | .forEach(System.out::println); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Filter.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_Filter { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4) // stream de 0 a 3 10 | .filter(e -> e % 2 == 0) // limita a números pares (resto da divisão por 2 é 0) 11 | .forEach(System.out::println); // imprime os elementos 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_FindFirstAny.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Optional; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_FindFirstAny { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Optional findFirst = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 11 | .findFirst(); // pega o primeiro número do Stream 12 | System.out.println("First: " + findFirst.get()); 13 | 14 | Optional findAny = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 15 | .findAny(); // pega qualquer número do Stream 16 | System.out.println("Any: " + findAny.get()); 17 | // end::code[] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_FlatMap.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_FlatMap { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | // Criação de 3 arrays distintos 11 | String[] array1 = new String[] { "A", "B", "C" }; 12 | String[] array2 = new String[] { "D", "E", "F" }; 13 | String[] array3 = new String[] { "G", "H", "I" }; 14 | 15 | Stream.of(array1, array2, array3) // criação de um Stream de Arrays 16 | .flatMap(a -> Arrays.stream(a)) // transforma os dados de cada array em um único fluxo de dados 17 | .forEach(System.out::println); // imprime os elementos 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_IntRangeStream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_IntRangeStream { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4).forEach(System.out::println); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_LazyMap.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_LazyMap { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 10) 10 | .peek(e -> System.out.println("Peek: " + e)) 11 | .limit(3) 12 | .forEach(e -> System.out.println("ForEach: " + e)); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_LazyNoFinal.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_LazyNoFinal { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4) 10 | .filter(e -> e % 2 == 0) 11 | .limit(3) 12 | .map(e -> e * 2) 13 | .peek(System.out::println); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Limit.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_Limit { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4) // stream de 0 a 3 10 | .limit(2) // limita a 2 elementos 11 | .forEach(System.out::println); // imprime os elementos 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_ListStream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Streams_ListStream { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList("A", "B", "C"); 11 | list.stream().forEach(System.out::println); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Map.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_Map { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4) // stream de 0 a 3 10 | .map(e -> e * 2) // multiplica os elementos por 2 11 | .forEach(System.out::println); // imprime os elementos 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Match.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_Match { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | boolean anyMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 10 | .anyMatch(e -> e > 5); // verifica se algum elemento é maior que 5 11 | System.out.println("anyMatch: " + anyMatch); 12 | 13 | boolean allMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 14 | .allMatch(e -> e > 5); // verifica se TODOS os elementos são maiores que 5 15 | System.out.println("allMatch: " + allMatch); 16 | 17 | boolean noneMatch = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 18 | .noneMatch(e -> e > 5); // verifica se NENHUM elemento é maior que 5 19 | System.out.println("noneMatch: " + noneMatch); 20 | 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_MaxMinCount.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Comparator; 4 | import java.util.Optional; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_MaxMinCount { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | Optional max = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 12 | .max(Comparator.naturalOrder()); // pega o maior número do Stream 13 | System.out.println("Max: " + max.get()); 14 | 15 | Optional min = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 16 | .min(Comparator.naturalOrder()); // pega o menor número do Stream 17 | System.out.println("Min: " + min.get()); 18 | 19 | long count = Stream.of(7, 2, 1, 8, 4, 9, 2, 8) // stream de vários Integer 20 | .count(); // pega a quantidade de elementos do Stream 21 | System.out.println("Count: " + count); 22 | // end::code[] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Of.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_Of { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Stream.of("A", 'B', 1, 2L, 3.0F, 4.0D).forEach(System.out::println); 10 | // end::code[] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Optional.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Comparator; 4 | import java.util.Optional; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_Optional { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Exemplo sem encadear a chamada de Optional 12 | Optional max = Stream.of(7, 2, 1) 13 | .max(Comparator.naturalOrder()); 14 | 15 | max.ifPresent(System.out::println); 16 | 17 | // Exemplo encadeando a chamada de Optional 18 | Stream.of(7, 2, 1) 19 | .max(Comparator.naturalOrder()) 20 | .ifPresent(System.out::println); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Peek.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Streams_Peek { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // Criação de um array comum de Strings 10 | String[] array = new String[] { "G", "T", "Y", "A" }; 11 | 12 | Arrays.stream(array) 13 | .peek(e -> System.out.println("Peek: " + e)) // observa o que passou pelo Stream 14 | .forEach(e -> System.out.println("ForEach: " + e)); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Pipeline.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_Pipeline { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 10) // Stream de 0 a 9 10 | .filter(e -> e % 2 == 0) // mantém apenas números pares 11 | .skip(2) // ignora os dois primeiros 12 | .limit(2) // limita a 3 elementos 13 | .map(e -> e * 2) // multipla cada elemento por 2 14 | .forEach(System.out::println); // imprime cada elemento 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_ReuseStream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_ReuseStream { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Stream stream = Stream.of(7, 2, 1); 10 | stream.forEach(System.out::println); // imprime elementos do Stream 11 | stream.forEach(System.out::println); // LANÇA EXCEÇÃO - o Stream já estava fechado 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Skip.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_Skip { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(0, 4) // stream de 0 a 3 10 | .skip(2) // ignora 2 elementos 11 | .forEach(System.out::println); // imprime os elementos 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/Streams_Sorted.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Streams_Sorted { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | // Criação de um array comum de Strings 10 | String[] array = new String[] { "G", "T", "Y", "A", "B", "C", "A", "B", "F" }; 11 | 12 | Arrays.stream(array) 13 | .sorted() // ordena utilizando a ordem natural 14 | .forEach(System.out::println); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorAveragingInt.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.stream.Collectors; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_CollectorAveragingInt { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | // Calcula a média do tamanho de cada nome 11 | Double collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 12 | .collect(Collectors.averagingInt(s -> s.length())); 13 | 14 | System.out.println(collect); 15 | // end::code[] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingBy.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class Streams_CollectorGroupingBy { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | // Armazena o resultado do Stream em um Mapa 13 | // A Chave é o tamanho do nome 14 | // O Valor é uma lista com os nomes que tem aquele tamanho 15 | Map> collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 16 | .collect(Collectors.groupingBy(s -> s.length())); 17 | 18 | System.out.println(collect); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByDownstream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_CollectorGroupingByDownstream { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Armazena o resultado do Stream em um Mapa 12 | // A Chave é o tamanho do nome 13 | // O Valor são os nomes que tem aquele tamanho 14 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 15 | .collect(Collectors.groupingBy(s -> s.length(), Collectors.joining(","))); 16 | 17 | System.out.println(collect); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorGroupingByMapFactory.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class Streams_CollectorGroupingByMapFactory { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | // Armazena o resultado do Stream em um Mapa 13 | // A Chave é o tamanho do nome 14 | // O Valor são os nomes que tem aquele tamanho 15 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 16 | .collect(Collectors.groupingBy(s -> s.length(), TreeMap::new, Collectors.joining(","))); 17 | 18 | System.out.println(collect); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorJoining.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.stream.Collectors; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_CollectorJoining { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | String collect = Stream.of("A", "B", "C") 11 | .collect(Collectors.joining()); 12 | 13 | System.out.println(collect); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorMapping.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_CollectorMapping { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Armazena o resultado do Stream em um Mapa 12 | // A Chave é o tamanho do nome 13 | // O Valor são os nomes que tem aquele tamanho, convertidos para maiúscula, separados por vírgula 14 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 15 | .collect(Collectors.groupingBy(s -> s.length(), Collectors.mapping(s -> s.toUpperCase(), Collectors.joining(",")))); 16 | 17 | System.out.println(collect); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningBy.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class Streams_CollectorPartitioningBy { 9 | 10 | public static void main(String[] args) { 11 | // tag::code[] 12 | // Armazena o resultado do Stream em um Mapa 13 | // As Chaves são true ou false 14 | // O Valor é uma lista dos valores que atendem ou não a regra de particionamento 15 | Map> collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 16 | .collect(Collectors.partitioningBy(s -> s.startsWith("R"))); 17 | 18 | System.out.println(collect); 19 | // end::code[] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorPartitioningByDownstream.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_CollectorPartitioningByDownstream { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Armazena o resultado do Stream em um Mapa 12 | // As Chaves são true ou false 13 | // O Valor é uma String que são os nomes que atendem ou não a regra de particionamento 14 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 15 | .collect(Collectors.partitioningBy(s -> s.startsWith("R"), Collectors.joining(","))); 16 | 17 | System.out.println(collect); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMap.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_CollectorToMap { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Armazena o resultado do Stream em um Mapa 12 | // A Chave é o próprio nome (s -> s) 13 | // O Valor é o tamanho do nome 14 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 15 | .collect(Collectors.toMap(s -> s, s -> s.length())); 16 | 17 | System.out.println(collect); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/collect/Streams_CollectorToMapDuplicateKey.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.collect; 2 | 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Streams_CollectorToMapDuplicateKey { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Armazena o resultado do Stream em um Mapa 12 | // A Chave é o tamanho do nome 13 | // O Valor são os nomes com aquele tamanho 14 | Map collect = Stream.of("Rinaldo", "Rodrigo", "Luiz", "Amélia", "Roseany") 15 | .collect(Collectors.toMap(s -> s.length(), s -> s, (s1, s2) -> s1 + "," + s2)); 16 | 17 | System.out.println(collect); 18 | // end::code[] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/primitives/Streams_Generate.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.primitives; 2 | 3 | import java.util.Random; 4 | import java.util.stream.DoubleStream; 5 | import java.util.stream.IntStream; 6 | 7 | public class Streams_Generate { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | // Cria Stream infinito de números aleatórios 12 | System.out.println(" IntStream infinito de números aleatórios"); 13 | IntStream.generate(() -> new Random().nextInt()) 14 | .limit(3) 15 | .forEach(System.out::println); 16 | 17 | System.out.println("\n DoubleStream infinito de números aleatórios"); 18 | DoubleStream.generate(Math::random) 19 | .limit(3) 20 | .forEach(System.out::println); 21 | // end::code[] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/primitives/Streams_MapTo.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.primitives; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Streams_MapTo { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | List list = Arrays.asList(1, 2, 3, 4); 11 | 12 | System.out.println(" Stream para IntStream"); 13 | list.stream() // cria Stream 14 | .mapToInt(Integer::intValue) // transforma em IntStream 15 | .forEach(System.out::print); 16 | 17 | System.out.println("\n Stream para LongStream"); 18 | list.stream() // cria Stream 19 | .mapToLong(Integer::longValue) // transforma em LongStream 20 | .forEach(System.out::print); 21 | 22 | System.out.println("\n Stream para DoubleStream"); 23 | list.stream() // cria Stream 24 | .mapToDouble(Integer::doubleValue) // transforma em DoubleStream 25 | .forEach(System.out::print); 26 | // end::code[] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/primitives/Streams_Primitives.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.primitives; 2 | 3 | import java.util.stream.DoubleStream; 4 | import java.util.stream.IntStream; 5 | import java.util.stream.LongStream; 6 | 7 | public class Streams_Primitives { 8 | 9 | public static void main(String[] args) { 10 | // tag::code[] 11 | System.out.println(" DoubleStream"); 12 | DoubleStream.of(1.1, 2.2, 3.3).forEach(System.out::print); 13 | 14 | System.out.println("\n IntStream"); 15 | IntStream.of(1, 2, 3).forEach(System.out::print); 16 | System.out.println(); 17 | IntStream.range(1, 4).forEach(System.out::print); 18 | 19 | System.out.println("\n LongStream"); 20 | LongStream.of(1, 2, 3).forEach(System.out::print); 21 | System.out.println(); 22 | LongStream.range(1, 4).forEach(System.out::print); 23 | // end::code[] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/primitives/Streams_RangeClosed.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.primitives; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class Streams_RangeClosed { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | IntStream.range(1, 4).forEach(System.out::print); 10 | System.out.println(); 11 | IntStream.rangeClosed(1, 4).forEach(System.out::print); 12 | // end::code[] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/primitives/Streams_Statistics.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.primitives; 2 | 3 | import java.util.IntSummaryStatistics; 4 | import java.util.stream.IntStream; 5 | 6 | public class Streams_Statistics { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | IntSummaryStatistics summaryStatistics = IntStream.range(0, 10).summaryStatistics(); 11 | System.out.println("Quantidade: " + summaryStatistics.getCount()); 12 | System.out.println("Maior: " + summaryStatistics.getMax()); 13 | System.out.println("Menor: " + summaryStatistics.getMin()); 14 | System.out.println("Soma: " + summaryStatistics.getSum()); 15 | System.out.println("Média: " + summaryStatistics.getAverage()); 16 | // end::code[] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/reduce/Streams_Reduce.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.reduce; 2 | 3 | import java.util.Optional; 4 | import java.util.stream.Stream; 5 | 6 | public class Streams_Reduce { 7 | 8 | public static void main(String[] args) { 9 | // tag::code[] 10 | Optional reduce = Stream.of(7, 2, 3, 8) 11 | .reduce((e1, e2) -> e1 * e2); // reduce que multiplica todos os números 12 | 13 | System.out.println(reduce.get()); 14 | // end::code[] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/reduce/Streams_ReduceCombiner.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.reduce; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_ReduceCombiner { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Integer reduce = Stream.of(7, 2, 3, 8) 10 | .reduce(1, (e1, e2) -> e1 * e2, (e1, e2) -> e1 * e2); 11 | 12 | System.out.println(reduce); 13 | // end::code[] 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/org/j6toj8/streams/usingstreams/reduce/Streams_ReduceIdentity.java: -------------------------------------------------------------------------------- 1 | package org.j6toj8.streams.usingstreams.reduce; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class Streams_ReduceIdentity { 6 | 7 | public static void main(String[] args) { 8 | // tag::code[] 9 | Integer reduce = Stream.of(7, 2, 3, 8) 10 | .reduce(1, (e1, e2) -> e1 * e2); 11 | 12 | System.out.println(reduce); 13 | // end::code[] 14 | } 15 | } 16 | --------------------------------------------------------------------------------