├── .gitattributes
├── .gitignore
├── .project
├── LICENSE
├── README.md
├── demo.txt
├── employees.xml
├── inventory.xml
├── logs
└── app.log
├── pom.xml
├── splash.png
└── src
└── main
├── java
└── com
│ ├── howtodoinjava
│ ├── algorithms
│ │ ├── BubbleSort.java
│ │ ├── InsertionSort.java
│ │ ├── IsomorphicStrings.java
│ │ ├── JumpSearchAlgorithm.java
│ │ ├── LinearSearch.java
│ │ ├── MergeSort.java
│ │ ├── Quicksort.java
│ │ └── README.md
│ ├── cleaner
│ │ ├── AppCleanerProvider.java
│ │ ├── ClassAccessingResource.java
│ │ ├── CleanerExample.java
│ │ └── Resource.java
│ ├── cloning
│ │ └── DeepCloningExample.java
│ ├── concurrency
│ │ ├── BlockingThreadPoolExecutor.java
│ │ ├── BlockingThreadPoolExecutorDemo.java
│ │ ├── CallableFutureExample.java
│ │ ├── CancelATask.java
│ │ ├── CustomRejectedExecutionHandler.java
│ │ ├── CustomThreadPoolExample.java
│ │ ├── CustomThreadPoolExecutor.java
│ │ ├── DemoExecutor.java
│ │ ├── DemoTask.java
│ │ ├── ForkJoinExample.java
│ │ ├── GetAndSetThreadNames.java
│ │ ├── IllegalMonitorStateExceptionDemo.java
│ │ ├── KillingAThread.java
│ │ ├── README.md
│ │ ├── ScheduledExecutorServiceExample.java
│ │ ├── SharedSeedExample.java
│ │ ├── ShutdownExecutor.java
│ │ ├── StartAThread.java
│ │ ├── ThreadJoiningInterrupt.java
│ │ ├── ThreadPoolExample.java
│ │ ├── ThreadPriorityDemo.java
│ │ ├── WaitForAllTasksToComplete.java
│ │ ├── interview
│ │ │ ├── DoNotOverrideRunMethod.java
│ │ │ ├── OverrideStartMethod.java
│ │ │ └── ThreadGroupExample.java
│ │ ├── threaddumps
│ │ │ ├── ThreadDeadlock.java
│ │ │ └── ThreadHighCPU.java
│ │ └── virtualThreads
│ │ │ └── ExecutorExample.java
│ ├── core
│ │ ├── PrimitiveStreams.java
│ │ ├── array
│ │ │ ├── ArrayCopy.java
│ │ │ ├── ArrayCopyRange.java
│ │ │ ├── ArrayDeepCopy.java
│ │ │ ├── ArrayExceptions.java
│ │ │ ├── ArrayListToArray.java
│ │ │ ├── ArraySortAlphabatical.java
│ │ │ ├── CheckIsSorted.java
│ │ │ ├── CompareArray.java
│ │ │ ├── ConcatArrays.java
│ │ │ ├── ConvertBetweenArrayAndList.java
│ │ │ ├── ConvertBetweenArrayAndStream.java
│ │ │ ├── ConvertBetweenPrimitiveAndObjects.java
│ │ │ ├── ConvertPrimitiveArrayToList.java
│ │ │ ├── ConvertStringArrayToIntArray.java
│ │ │ ├── FindMaxMin.java
│ │ │ ├── InitializeArrays.java
│ │ │ ├── Intersection.java
│ │ │ ├── JoinArrayItems.java
│ │ │ ├── Print2dArray.java
│ │ │ ├── PrintArray.java
│ │ │ ├── README.md
│ │ │ ├── RemoveArrayItems.java
│ │ │ ├── RemoveDuplicates.java
│ │ │ ├── ResizeArray.java
│ │ │ ├── ReverseArray.java
│ │ │ ├── SortStringAlphabetically.java
│ │ │ ├── SplitArray.java
│ │ │ ├── SumAndAverageOfArray.java
│ │ │ ├── TopNItems.java
│ │ │ ├── Union.java
│ │ │ └── User.java
│ │ ├── basic
│ │ │ ├── AllPrimeFactors.java
│ │ │ ├── AssertExample.java
│ │ │ ├── BusinessCustomer.java
│ │ │ ├── CharacterEncodingExample.java
│ │ │ ├── Customer.java
│ │ │ ├── ForEachExamples.java
│ │ │ ├── ForLoopExample.java
│ │ │ ├── ForLoopPerformanceTest.java
│ │ │ ├── HelpfulNullPointerExceptionExample.java
│ │ │ ├── InstanceOfExample.java
│ │ │ ├── InstanceOfOperatorExample.java
│ │ │ ├── MainClass.java
│ │ │ ├── ObjectIdentityString.java
│ │ │ ├── PersonalCustomer.java
│ │ │ ├── PrintFormattedOutput.java
│ │ │ ├── README.md
│ │ │ ├── RegexExamples.java
│ │ │ ├── RoundOffFloats.java
│ │ │ ├── StricfpExample.java
│ │ │ ├── StringPoolExample.java
│ │ │ ├── SubStringExample.java
│ │ │ ├── SwitchExpressions.java
│ │ │ ├── SwitchStatement.java
│ │ │ ├── TextBlocks.java
│ │ │ ├── UnderscoreInLiterals.java
│ │ │ ├── WhileLoopExample.java
│ │ │ ├── math
│ │ │ │ ├── MathAbsoluteExamples.java
│ │ │ │ ├── MathDivideExact.java
│ │ │ │ └── MathFloorDivCeilDiv.java
│ │ │ └── record
│ │ │ │ ├── BuilderExample.java
│ │ │ │ ├── Employee.java
│ │ │ │ ├── GenericRecordExample.java
│ │ │ │ └── RecordExample.java
│ │ ├── collections
│ │ │ ├── AddMultipleItems.java
│ │ │ ├── ArrayListToLinkedList.java
│ │ │ ├── ConvertArrayToList.java
│ │ │ ├── ConvertSetToList.java
│ │ │ ├── IterateOverCollection.java
│ │ │ ├── cursors
│ │ │ │ ├── AlternateNextAndPrevious.java
│ │ │ │ ├── ConcurrentModification.java
│ │ │ │ ├── EnumerationCursor.java
│ │ │ │ ├── IteratorCursor.java
│ │ │ │ ├── ListIteratorCursor.java
│ │ │ │ ├── SpliteratorCursor.java
│ │ │ │ └── SpliteratorEstimateSize.java
│ │ │ ├── list
│ │ │ │ ├── AddItem.java
│ │ │ │ ├── ArrayListExamples.java
│ │ │ │ ├── ArrayListSort.java
│ │ │ │ ├── CheckEmptyList.java
│ │ │ │ ├── ClearArrayList.java
│ │ │ │ ├── EqualListsIgnoringOrder.java
│ │ │ │ ├── FlattenNestedList.java
│ │ │ │ ├── ListDifference.java
│ │ │ │ ├── MergeArrayLists.java
│ │ │ │ ├── README.md
│ │ │ │ ├── RemoveDuplicates.java
│ │ │ │ ├── RemoveIf.java
│ │ │ │ ├── ReplaceItem.java
│ │ │ │ ├── RetainsAll.java
│ │ │ │ ├── SerializationDeserialization.java
│ │ │ │ └── Task.java
│ │ │ ├── map
│ │ │ │ ├── ConcurrentMapExample.java
│ │ │ │ ├── ConcurrentSkipListMapExample.java
│ │ │ │ ├── ConcurrentSkipListMapExamples.java
│ │ │ │ ├── ConvertListToMap.java
│ │ │ │ ├── EnumMapExamples.java
│ │ │ │ ├── HashMapExamples.java
│ │ │ │ ├── IdentityHashMapExample.java
│ │ │ │ ├── ImmutableMap.java
│ │ │ │ ├── InitializeHashMap.java
│ │ │ │ ├── InvertedMap.java
│ │ │ │ ├── MapComputeIfAbsent.java
│ │ │ │ ├── MapDifferenceDemo.java
│ │ │ │ ├── MaxMin.java
│ │ │ │ ├── MergeMaps.java
│ │ │ │ ├── NestedMap.java
│ │ │ │ ├── PerformanceCompareForIterations.java
│ │ │ │ ├── README.md
│ │ │ │ ├── ShallowDeepCopy.java
│ │ │ │ ├── SortAMapByKeysAndValues.java
│ │ │ │ ├── SubMaps.java
│ │ │ │ ├── SynchronizedMaps.java
│ │ │ │ ├── UnmodifiableMap.java
│ │ │ │ └── WeekHashMapExample.java
│ │ │ └── queue
│ │ │ │ ├── JavaQueueExamples.java
│ │ │ │ ├── PriorityQueueExample.java
│ │ │ │ ├── PriortyQueueWithCustomObject.java
│ │ │ │ ├── QueueDrain.java
│ │ │ │ └── README.md
│ │ ├── datatypes
│ │ │ ├── ConvertIntToString.java
│ │ │ ├── Employee.java
│ │ │ └── decimalandhexadecimal
│ │ │ │ ├── BinaryOctalAndHex.java
│ │ │ │ ├── decimaltohex
│ │ │ │ ├── ExampleUsingBigIntegerClass.java
│ │ │ │ ├── ExampleUsingDouble.java
│ │ │ │ ├── ExampleUsingIntegerClass.java
│ │ │ │ ├── ExampleUsingLongClass.java
│ │ │ │ ├── ExampleUsingRawMethod.java
│ │ │ │ ├── ExampleUsingStringClass.java
│ │ │ │ └── FloatingPointDecimalToHex.java
│ │ │ │ └── hextodecimal
│ │ │ │ ├── ExampleUsingBigIntegerClass.java
│ │ │ │ ├── ExampleUsingIntegerClass.java
│ │ │ │ ├── ExampleUsingLongClass.java
│ │ │ │ ├── ExampleUsingRawMethod.java
│ │ │ │ └── FloatingPointHexToDecimal.java
│ │ ├── datetime
│ │ │ ├── AddHoursMinutesSecondsToDate.java
│ │ │ ├── BusinessDaysExamples.java
│ │ │ ├── ChangingTimeZones.java
│ │ │ ├── CheckWeekendJava7.java
│ │ │ ├── CheckWeekendJava8.java
│ │ │ ├── CompareLocalDateTimes.java
│ │ │ ├── CompareLocalDates.java
│ │ │ ├── CompareZonedDateTimes.java
│ │ │ ├── ConvertBetweenMonthNameAndNumber.java
│ │ │ ├── CurrentDateTime.java
│ │ │ ├── CurrentTimeStamp.java
│ │ │ ├── DateComparison.java
│ │ │ ├── DateConversionUtils.java
│ │ │ ├── DateDifference.java
│ │ │ ├── DateFormatting.java
│ │ │ ├── DateTimeExample.java
│ │ │ ├── DateTimeFormatterWithTimeZone.java
│ │ │ ├── DayOfWeekExample.java
│ │ │ ├── DayPeriodFormatter.java
│ │ │ ├── DaysBetweenDates.java
│ │ │ ├── DisplayDayOfWeekName.java
│ │ │ ├── ElapsedTimeSinceMidnight.java
│ │ │ ├── EstTimezone.java
│ │ │ ├── ExtractDayMonthYear.java
│ │ │ ├── FindDayOfWeek.java
│ │ │ ├── FindNextPrevDay.java
│ │ │ ├── FirstAndLastDay.java
│ │ │ ├── FirstLastDayOfYear.java
│ │ │ ├── FormatLocalDate.java
│ │ │ ├── FormatLocalDateTime.java
│ │ │ ├── FormatMilliseconds.java
│ │ │ ├── FormatZonedDateTime.java
│ │ │ ├── FormattingDates.java
│ │ │ ├── GetAllDatesBetweenTwoDates.java
│ │ │ ├── GetQuarterInfo.java
│ │ │ ├── InstantToLocalDateTime.java
│ │ │ ├── InstantToZonedDateTime.java
│ │ │ ├── JavaDateValidations.java
│ │ │ ├── ListOfTimezoneIds.java
│ │ │ ├── LocaleExamples.java
│ │ │ ├── LocationBasedDateFormatting.java
│ │ │ ├── NewDateTimeAPI.java
│ │ │ ├── ParseZonedDateTime.java
│ │ │ ├── PeriodExample.java
│ │ │ ├── README.md
│ │ │ ├── SetJvmTimezone.java
│ │ │ ├── SplitDateRangeIntoEqualIntervals.java
│ │ │ ├── StartEndOfDay.java
│ │ │ ├── StopWatchExamples.java
│ │ │ ├── TemporalAdjusterExamples.java
│ │ │ ├── TemporalQueriesExample.java
│ │ │ ├── ValidateMultipleDateFormats.java
│ │ │ ├── WeeksBetweenDates.java
│ │ │ └── XmlGregorianCalendarExamples.java
│ │ ├── enums
│ │ │ ├── EnumExamples.java
│ │ │ ├── EnumWithMultipleValues.java
│ │ │ ├── EnumWithStringsExample.java
│ │ │ └── PathUtils.java
│ │ ├── examples
│ │ │ ├── AddTwoIntegers.java
│ │ │ ├── AgeCalculator.java
│ │ │ ├── CalculateAverage.java
│ │ │ ├── ConsoleExamples.java
│ │ │ └── README.md
│ │ ├── exceptions
│ │ │ ├── StackTrace.java
│ │ │ └── SuppressedException.java
│ │ ├── jmh
│ │ │ └── IntToStringBenchmark.java
│ │ ├── objectToMap
│ │ │ ├── ConvertObjectToMapExample.java
│ │ │ ├── Employee.java
│ │ │ └── README.md
│ │ ├── optional
│ │ │ └── OptionalExamples.java
│ │ ├── predicate
│ │ │ └── IntPredicateExample.java
│ │ ├── random
│ │ │ ├── README.md
│ │ │ ├── RandomNumberStream.java
│ │ │ ├── RandomNumbersInRange.java
│ │ │ └── SimpleRandoms.java
│ │ ├── recursion
│ │ │ ├── RecursionDemo.java
│ │ │ └── RecursiveCall.java
│ │ ├── security
│ │ │ ├── AES.java
│ │ │ ├── AES256.java
│ │ │ ├── AES256Example.java
│ │ │ ├── Base64Example.java
│ │ │ ├── Base64FileEncodeExample.java
│ │ │ ├── EdwardAlgoExample.java
│ │ │ └── concurrent
│ │ │ │ ├── AES256EncryptionTask.java
│ │ │ │ └── Demo.java
│ │ ├── serialization
│ │ │ ├── DeepCopyDemo.java
│ │ │ ├── SerializeObjectToString.java
│ │ │ └── TestClass.java
│ │ ├── sorting
│ │ │ ├── ComparableExamples.java
│ │ │ ├── ComparatorExamples.java
│ │ │ ├── FirstNameSorter.java
│ │ │ └── User.java
│ │ ├── streams
│ │ │ ├── AddRemoveItems.java
│ │ │ ├── BoxedStreamExample.java
│ │ │ ├── ChainedPredicate.java
│ │ │ ├── CreateStreams.java
│ │ │ ├── Employee.java
│ │ │ ├── FilterAMap.java
│ │ │ ├── FilteringNestedCollections.java
│ │ │ ├── HandleCheckedExceptions.java
│ │ │ ├── IfElseLogic.java
│ │ │ ├── Main.java
│ │ │ ├── MapMultiExample.java
│ │ │ ├── MatchAllExample.java
│ │ │ ├── MaxDateExample.java
│ │ │ ├── MethodReferenceVsLambdaExamples.java
│ │ │ ├── Person.java
│ │ │ ├── PrimitiveStreams.java
│ │ │ ├── README.md
│ │ │ ├── RemoveOrUpdateElements.java
│ │ │ ├── StreamContainsAnyContainsAll.java
│ │ │ ├── StreamOfDates.java
│ │ │ ├── StreamOfRandomNumbers.java
│ │ │ ├── TeeingCollectorExample.java
│ │ │ ├── collect
│ │ │ │ ├── CollectStreamItemsToMap.java
│ │ │ │ ├── GroupingByExamples.java
│ │ │ │ └── StreamCollectToImmutableCollections.java
│ │ │ ├── conversions
│ │ │ │ ├── EnumToStream.java
│ │ │ │ ├── IterableToStream.java
│ │ │ │ ├── IteratorToStream.java
│ │ │ │ └── StreamToList.java
│ │ │ ├── distinct
│ │ │ │ ├── DistinctComplexTypes.java
│ │ │ │ └── DistinctPrimitivesAndStrings.java
│ │ │ ├── duplicates
│ │ │ │ └── RemoveDuplicatesFromList.java
│ │ │ ├── intstream
│ │ │ │ ├── FilterExample.java
│ │ │ │ ├── ForEachExample.java
│ │ │ │ └── RangeExample.java
│ │ │ ├── methods
│ │ │ │ └── ForEach.java
│ │ │ ├── misc
│ │ │ │ ├── AppendPrepend.java
│ │ │ │ └── GetLastElement.java
│ │ │ ├── predicates
│ │ │ │ └── TestPredicates.java
│ │ │ └── sort
│ │ │ │ ├── DateOfBirthComparator.java
│ │ │ │ ├── FirstNameSorter.java
│ │ │ │ ├── NumberStream.java
│ │ │ │ ├── SortWithNullValues.java
│ │ │ │ ├── StringStream.java
│ │ │ │ └── UserTypeStream.java
│ │ └── string
│ │ │ ├── AlignOutputToColumns.java
│ │ │ ├── Cancat.java
│ │ │ ├── ChatAt.java
│ │ │ ├── CompareTo.java
│ │ │ ├── CompareToIgnoreCase.java
│ │ │ ├── Contains.java
│ │ │ ├── DuplicateWords.java
│ │ │ ├── EndsWith.java
│ │ │ ├── Equals.java
│ │ │ ├── FindDuplicateCharacters.java
│ │ │ ├── IndexOf.java
│ │ │ ├── Intern.java
│ │ │ ├── LastIndexOf.java
│ │ │ ├── LeftRightPad.java
│ │ │ ├── Lowercase.java
│ │ │ ├── MaskExceptLast4Chars.java
│ │ │ ├── MultilineStringExample.java
│ │ │ ├── README.md
│ │ │ ├── RemoveLastCharacter.java
│ │ │ ├── Replace.java
│ │ │ ├── ReplaceAll.java
│ │ │ ├── ReplaceFirst.java
│ │ │ ├── ReverseString.java
│ │ │ ├── ReverseWords.java
│ │ │ ├── SplitCSV.java
│ │ │ ├── StartsWith.java
│ │ │ ├── StringAlignExample.java
│ │ │ ├── StringAlignment.java
│ │ │ ├── StringConcatenationBenchmark.java
│ │ │ ├── StringEquality.java
│ │ │ ├── StringIndentExample.java
│ │ │ ├── StringJoinerExamples.java
│ │ │ ├── StringToInt.java
│ │ │ ├── SubString.java
│ │ │ ├── TextBlockFormatting.java
│ │ │ ├── TitleCase.java
│ │ │ └── UnescapeHTML.java
│ ├── csv
│ │ ├── demoOpenCSV
│ │ │ └── OpenCSVExample.java
│ │ ├── demoScanner
│ │ │ └── ScannerExample.java
│ │ └── demoSplit
│ │ │ └── SplitterExample.java
│ ├── datastructure
│ │ ├── CustomList.java
│ │ ├── Stack.java
│ │ ├── TestListImpl.java
│ │ └── TestStackImpl.java
│ ├── exercise
│ │ └── ArrayTwoSum.java
│ ├── hashing
│ │ └── password
│ │ │ └── demo
│ │ │ ├── advanced
│ │ │ └── ReallyStrongSecuredPassword.java
│ │ │ ├── bcrypt
│ │ │ ├── BCrypt.java
│ │ │ └── BcryptHashingExample.java
│ │ │ ├── md5
│ │ │ ├── FileChecksum.java
│ │ │ ├── SaltedMD5Example.java
│ │ │ └── SimpleMD5Example.java
│ │ │ ├── scrypt
│ │ │ └── ScryptPasswordHashingDemo.java
│ │ │ └── sha
│ │ │ └── SHAExample.java
│ ├── io
│ │ ├── CheckEmptyDirectory.java
│ │ ├── CheckIfFileExists.java
│ │ ├── ConvertReaderToString.java
│ │ ├── CopyDirectoryExample.java
│ │ ├── CountFileLines.java
│ │ ├── CreateAFile.java
│ │ ├── CreateDirectory.java
│ │ ├── CreateTempFile.java
│ │ ├── DeleteAFile.java
│ │ ├── DeleteFileContent.java
│ │ ├── FileCopyExample.java
│ │ ├── FileCreationTime.java
│ │ ├── FileFilterExample.java
│ │ ├── FilePath.java
│ │ ├── FileReaderExample.java
│ │ ├── FileSize.java
│ │ ├── FileWriterExample.java
│ │ ├── FilenameFilterExample.java
│ │ ├── FindAFileInDirectory.java
│ │ ├── InputStreamReaderExample.java
│ │ ├── InputStreamToOutputStream.java
│ │ ├── IterateDirectoryExample.java
│ │ ├── PropertiesCacheExample.java
│ │ ├── README.md
│ │ ├── ReadCSV.java
│ │ ├── ReadFileFromClasspath.java
│ │ ├── ReadFileFromResourcesUsingGetResource.java
│ │ ├── ReadFileFromResourcesUsingGetResourceAsStream.java
│ │ ├── ReadFileLineByLine.java
│ │ ├── ReadFileToByteArray.java
│ │ ├── ReadFileToList.java
│ │ ├── ReadFileToString.java
│ │ ├── ReadFileWithChannels.java
│ │ ├── ReadGivenLineFromFile.java
│ │ ├── ReadLargeFiles.java
│ │ ├── ReadOnlyFile.java
│ │ ├── ReaderToInputStream.java
│ │ ├── ReadwriteUTF8Data.java
│ │ ├── RenameFile.java
│ │ ├── StringReaderExample.java
│ │ ├── SymbolicLinkExamples.java
│ │ ├── WriteByteArrayToFile.java
│ │ ├── WriteToFile.java
│ │ ├── WriteToTempFile.java
│ │ └── foo
│ │ │ ├── bar
│ │ │ └── bar.txt
│ │ │ └── foo.txt
│ ├── jaxb
│ │ ├── Main.java
│ │ ├── MarshalListExample.java
│ │ ├── NoDefaultConstructor.java
│ │ ├── ReadWriteXML.java
│ │ └── XmlTypeAdapterOverInterface.java
│ ├── json
│ │ └── JsonArrayToList.java
│ ├── loom
│ │ └── HelloLoom.java
│ ├── mail
│ │ ├── EmailSender.java
│ │ ├── EmailSenderWithSSL.java
│ │ └── MailTest.java
│ ├── misc
│ │ ├── JFrameDemo.java
│ │ ├── TupleExamples.java
│ │ └── UnitTuple.java
│ ├── newFeatures
│ │ └── java21
│ │ │ ├── README.md
│ │ │ ├── ScopedValueTest.java
│ │ │ ├── SequencedCollectionExamples.java
│ │ │ ├── StringTemplates.java
│ │ │ ├── StructuredConcurrency.java
│ │ │ ├── UnnamedClassAndInstanceMainMethod.java
│ │ │ ├── UnnamedPatterns.java
│ │ │ └── UnnamedVariables.java
│ ├── puzzles
│ │ ├── Anagram.java
│ │ ├── ArrayRotation.java
│ │ ├── BalancedParenthesesChecker.java
│ │ ├── CheckAllAlphabetsAlgorithms.java
│ │ ├── CommonElementsInArrays.java
│ │ ├── Factorial.java
│ │ ├── FindAllDuplicateNumbers.java
│ │ ├── FindMissingNumberFromSeries.java
│ │ ├── FizzBuzz.java
│ │ ├── GoodStringBadString.java
│ │ ├── HiLo.java
│ │ ├── IdentifyProblemsInCode.java
│ │ ├── LargestElementFinder.java
│ │ ├── LongestSubstringLength.java
│ │ ├── MapPutOperation.java
│ │ ├── NthLongestStringAlgorithm.java
│ │ ├── Palindrome.java
│ │ ├── PlayHiLoGame.java
│ │ ├── README.md
│ │ ├── ReverseAString.java
│ │ └── TwoSum.java
│ ├── reflection
│ │ └── CallingInterfaceMethodWithoutImplementing.java
│ ├── regex
│ │ ├── MaxMinLength.java
│ │ ├── Misspelling.java
│ │ └── StartsWithEndsWith.java
│ ├── xml
│ │ ├── CheckIfNodeExists.java
│ │ ├── ConvertStringToXML.java
│ │ ├── DomParserExample.java
│ │ ├── GetNodesByAttributeValue.java
│ │ ├── GetXmlAttributeValue.java
│ │ ├── NamespaceResolution.java
│ │ ├── README.md
│ │ ├── XPathExample.java
│ │ ├── model
│ │ │ ├── Department.java
│ │ │ └── Employee.java
│ │ ├── sax
│ │ │ ├── SaxParserDemo.java
│ │ │ ├── User.java
│ │ │ ├── UserParser.java
│ │ │ └── UserParserHandler.java
│ │ └── stax
│ │ │ ├── ReadXmlWithCursor.java
│ │ │ └── ReadXmlWithIterator.java
│ └── zip
│ │ ├── UnzipExample.java
│ │ └── UnzipWithCommonCompress.java
│ └── lambdaworks
│ ├── codec
│ └── Base64.java
│ ├── crypto
│ ├── PBKDF.java
│ ├── SCrypt.java
│ └── SCryptUtil.java
│ └── jni
│ ├── JarLibraryLoader.java
│ ├── LibraryLoader.java
│ ├── LibraryLoaders.java
│ ├── NilLibraryLoader.java
│ ├── Platform.java
│ ├── SysLibraryLoader.java
│ └── UnsupportedPlatformException.java
└── resources
├── SampleCSVFile.csv
├── application.properties
├── data.json
├── data
└── demo.txt
├── dataOut.txt
├── demo.txt
└── threaddumps
├── Fast_thread_report-Threaddumps.pdf
├── ThreadDump_high_CPU.txt
└── Threaddumps.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries
2 | *.7z
3 | *.dmg
4 | *.gz
5 | *.iso
6 | *.jar1
7 | *.rar
8 | *.tar
9 | *.zip
10 | *.war
11 | *.ear
12 | *.sar
13 | *.class
14 |
15 | # class files
16 | bin/
17 | target/
18 |
19 | # eclipse project file
20 | .settings/
21 | .classpath
22 | .project
23 |
24 | # OS
25 | .DS_Store
26 |
27 | # Misc
28 | *.swp
29 | .metadata
30 | release.properties
31 | .classpath
32 | .project
33 | .factorypath
34 |
35 | .idea/
36 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Core-Java
4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.
5 |
6 |
7 |
8 |
9 | org.eclipse.wst.common.project.facet.core.builder
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.m2e.core.maven2Builder
20 |
21 |
22 |
23 |
24 |
25 | org.eclipse.m2e.core.maven2Nature
26 | org.eclipse.jdt.core.javanature
27 | org.eclipse.wst.common.project.facet.core.nature
28 |
29 |
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/README.md
--------------------------------------------------------------------------------
/demo.txt:
--------------------------------------------------------------------------------
1 | hello world !!
--------------------------------------------------------------------------------
/employees.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Lokesh
6 | Gupta
7 |
8 | 101
9 | IT
10 |
11 |
12 |
13 |
14 | Brian
15 | Schultz
16 |
17 | 102
18 | HR
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/inventory.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Snow Crash
6 | Neal Stephenson
7 | Spectra
8 | 0553380958
9 | 14.95
10 |
11 |
12 | Burning Tower
13 | Larry Niven
14 | Jerry Pournelle
15 | Pocket
16 | 0743416910
17 | 5.99
18 |
19 |
20 | Zodiac
21 | Neal Stephenson
22 | Spectra
23 | 0553573862
24 | 7.50
25 |
26 |
--------------------------------------------------------------------------------
/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/splash.png
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/algorithms/IsomorphicStrings.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.algorithms;
2 |
3 | public class IsomorphicStrings {
4 |
5 | public boolean areIsomorphic(String s1, String s2) {
6 | if (s1 == null || s2 == null
7 | || s1.length() != s2.length()) {
8 | return false;
9 | }
10 |
11 | int[] arr1 = new int[256];
12 | int[] arr2 = new int[256];
13 |
14 | for (int i = 0; i < s1.length(); i++) {
15 |
16 | char c1 = s1.charAt(i);
17 | char c2 = s2.charAt(i);
18 |
19 | if (arr1[c1] != arr2[c2]) {
20 | return false;
21 | }
22 |
23 | arr1[c1] = i + 1;
24 | arr2[c2] = i + 1;
25 | }
26 | return true;
27 | }
28 |
29 | public static void main(String[] args) {
30 | IsomorphicStrings iso = new IsomorphicStrings();
31 | System.out.println(iso.areIsomorphic("abbcdd", "qwwcrr")); // true
32 | System.out.println(iso.areIsomorphic("aab", "que")); // false
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/algorithms/JumpSearchAlgorithm.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.algorithms;
2 |
3 | public class JumpSearchAlgorithm {
4 |
5 | public static void main(String[] args) {
6 | int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
7 | int ele = 60;
8 |
9 | int foundIndex = jumpSearch(arr, ele);
10 | System.out.println(foundIndex > 0 ? "Found at index : " + foundIndex : "Element Not Found");
11 | }
12 |
13 | public static int jumpSearch(int[] arr, int ele) {
14 |
15 | int prev = 0;
16 | int n = arr.length;
17 | int step = (int) Math.floor(Math.sqrt(n));
18 |
19 | //loop until current element is less than the given search element
20 | while (arr[Math.min(step, n) - 1] < ele) {
21 | prev = step;
22 | step += (int) Math.floor(Math.sqrt(n));
23 | if (prev >= n) return -1;
24 | }
25 |
26 | //perform linear search prev index element to given element
27 | while (arr[prev] < ele) {
28 | prev++;
29 | if (prev == Math.min(step, n)) return -1;
30 | }
31 |
32 | // Return index if element is found
33 | if (arr[prev] == ele) return prev;
34 |
35 | return -1;
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/algorithms/LinearSearch.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.algorithms;
2 |
3 | class LinearSearch {
4 | public static void main(String args[]) {
5 |
6 | //given an array of elements
7 | int[] arr = {3, 4, 1, 7, 5};
8 |
9 | //given search element
10 | int ele = 7;
11 |
12 | //get length of the array
13 | int n = arr.length;
14 |
15 | //call lnrSearch method and display returned result
16 | System.out.println(lnrSearch(arr, n, ele));
17 | }
18 |
19 | //method to check for a element using linear search
20 | static String lnrSearch(int arr[], int n, int ele) {
21 | for (int i = 0; i < n; i++) {
22 | //checks for matching element
23 | if (arr[i] == ele)
24 | return "Given element is found at the index " + i;
25 | }
26 | return "Given element is not found in the array.";
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/algorithms/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 | * [Linear Search Algorithm](https://howtodoinjava.com/algorithm/linear-search/)
3 | * [Jump Search Algorithm](https://howtodoinjava.com/algorithm/jump-search-algorithm/)
4 | * [Merge Sort Algorithm](https://howtodoinjava.com/algorithm/merge-sort-java-example/)
5 | * [Bubble Sort Algorithm](https://howtodoinjava.com/algorithm/bubble-sort-java-example/)
6 |
7 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/cleaner/AppCleanerProvider.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.cleaner;
2 |
3 | import java.lang.ref.Cleaner;
4 |
5 | public class AppCleanerProvider {
6 | private static final Cleaner CLEANER = Cleaner.create();
7 |
8 | public static Cleaner getCleaner() {
9 | return CLEANER;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/cleaner/CleanerExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.cleaner;
2 |
3 | public class CleanerExample {
4 |
5 | public static void main(final String[] args) throws Exception {
6 |
7 | //1 Implicit Cleanup
8 | try (final ClassAccessingResource clazzInstance
9 | = new ClassAccessingResource()) {
10 | // Safely use the resource
11 | clazzInstance.businessOperation();
12 | clazzInstance.anotherBusinessOperation();
13 | }
14 |
15 | //2 Explicit Cleanup
16 | final ClassAccessingResource clazzInstance = new ClassAccessingResource();
17 | clazzInstance.businessOperation();
18 | clazzInstance.anotherBusinessOperation();
19 | clazzInstance.close();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/cleaner/Resource.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.cleaner;
2 |
3 | public class Resource {
4 | //Demo resource
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/BlockingThreadPoolExecutorDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | import java.util.concurrent.ArrayBlockingQueue;
4 | import java.util.concurrent.BlockingQueue;
5 | import java.util.concurrent.TimeUnit;
6 |
7 | public class BlockingThreadPoolExecutorDemo {
8 | public static void main(String[] args) throws InterruptedException {
9 | BlockingQueue blockingQueue = new ArrayBlockingQueue<>(1);
10 | BlockingThreadPoolExecutor executor = new BlockingThreadPoolExecutor(1, 1, 5000, TimeUnit.MILLISECONDS, blockingQueue);
11 | executor.setRejectedExecutionHandler(new CustomRejectedExecutionHandler());
12 |
13 | executor.prestartAllCoreThreads();
14 |
15 | int threadCounter = 0;
16 | while (true) {
17 | threadCounter++;
18 | // Adding threads one by one
19 | System.out.println("Adding DemoTask : " + threadCounter);
20 | blockingQueue.offer(new DemoTask(Integer.toString(threadCounter)));
21 | if (threadCounter == 100)
22 | break;
23 | }
24 |
25 | Thread.sleep(1000000);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/CallableFutureExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | import java.time.LocalDateTime;
4 | import java.util.concurrent.*;
5 |
6 | public class CallableFutureExample {
7 | public static void main(String[] args) throws ExecutionException,
8 | InterruptedException, TimeoutException {
9 |
10 | ExecutorService executor = Executors.newFixedThreadPool(1);
11 | Future future = executor.submit(new Work("Demo-Task"));
12 |
13 | String completedThread = future.get(10, TimeUnit.SECONDS);
14 |
15 | System.out.println("Thread completed : " + completedThread);
16 | }
17 | }
18 |
19 | class Work implements Callable {
20 | private final String name;
21 |
22 | public Work(String name) {this.name = name;}
23 |
24 | @Override
25 | public String call() {
26 | System.out.println("Task [" + name + "] executed on : " + LocalDateTime.now().toString());
27 | return name;
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/CancelATask.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | import java.util.concurrent.Executors;
4 | import java.util.concurrent.ScheduledExecutorService;
5 | import java.util.concurrent.ScheduledFuture;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | public class CancelATask {
9 | public static void main(String[] args) {
10 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
11 |
12 | ScheduledFuture> future = executor
13 | .schedule(() -> { System.out.println("Some Task"); }, 5, TimeUnit.SECONDS);
14 |
15 | System.out.println("Before Cancel - Task is done : " + future.isDone());
16 | System.out.println("Before Cancel - Task is cancel : " + future.isCancelled());
17 |
18 | if (future.isDone() == false) {
19 | future.cancel(false);
20 | }
21 |
22 | System.out.println("Before Cancel - Task is done : " + future.isDone());
23 | System.out.println("Before Cancel - Task is cancel : " + future.isCancelled());
24 |
25 | executor.shutdown();
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/CustomRejectedExecutionHandler.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | import java.util.concurrent.RejectedExecutionHandler;
4 | import java.util.concurrent.ThreadPoolExecutor;
5 |
6 | public class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
7 | @Override
8 | public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
9 | try
10 | {
11 | Thread.sleep(1000);
12 | System.out.println("Try again : " + ((DemoTask) r).getName());
13 | executor.execute(r);
14 | } catch (Exception e) {
15 | e.printStackTrace();
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/DemoExecutor.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | import java.util.concurrent.BlockingQueue;
4 | import java.util.concurrent.LinkedBlockingQueue;
5 | import java.util.concurrent.ThreadPoolExecutor;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | public class DemoExecutor {
9 | public static void main(String[] args) throws InterruptedException {
10 | BlockingQueue blockingQueue =
11 | new LinkedBlockingQueue();
12 |
13 | CustomThreadPoolExecutor executor =
14 | new CustomThreadPoolExecutor(10, 20, 5, TimeUnit.SECONDS,
15 | blockingQueue, new ThreadPoolExecutor.AbortPolicy());
16 |
17 | // Let start all core threads initially
18 | executor.prestartAllCoreThreads();
19 |
20 | for (int i = 1; i <= 100; i++) {
21 | blockingQueue.offer(new DemoTask("Task " + i));
22 | }
23 |
24 | executor.shutdown();
25 | executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/DemoTask.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | public class DemoTask implements Runnable {
4 | private String name = null;
5 |
6 | public DemoTask(String name) {
7 | this.name = name;
8 | }
9 |
10 | public String getName() {
11 | return this.name;
12 | }
13 |
14 | @Override
15 | public void run() {
16 | System.out.println("Executing : " + name);
17 | try {
18 | Thread.sleep(1000);
19 | } catch (InterruptedException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | 1. [How to Wait for Running Threads to Finish](https://howtodoinjava.com/java/multi-threading/wait-for-threads-to-finish/)
4 | 2. [Guide to Java ConcurrentMap](https://howtodoinjava.com/java/collections/java-concurrentmap/)
5 | 3. [How to Cancel a Task in ExecutorService](https://howtodoinjava.com/java/multi-threading/executor-service-cancel-task/)
6 | 4. [How to Shutdown a Java ExecutorService](https://howtodoinjava.com/java/multi-threading/executorservice-shutdown/)
7 | 5. [Java Fork/Join Framework Tutorial](https://howtodoinjava.com/java7/forkjoin-framework-tutorial-forkjoinpool-example/)
8 | 6. [Java Thread Pools and ThreadPoolExecutor](https://howtodoinjava.com/java/multi-threading/java-thread-pool-executor-example/)
9 | 7. [Kill a Thread in Java](https://howtodoinjava.com/java/multi-threading/killing-java-threads/)
10 | 8. [Thread Priority](https://howtodoinjava.com/java/multi-threading/java-thread-priority/)
11 | 9. [Start a New Thread](https://howtodoinjava.com/java/multi-threading/create-start-threads/)
12 | 10. [Resolving IllegalMonitorStateException In Java](https://howtodoinjava.com/java/multi-threading/java-illegalmonitorstateexception/)
13 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/ThreadJoiningInterrupt.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | public class ThreadJoiningInterrupt {
4 |
5 | public static void main(String[] args) {
6 |
7 | ChildThread childThread = new ChildThread(Thread.currentThread());
8 | childThread.start();
9 |
10 | try {
11 | childThread.join();
12 | } catch (InterruptedException ie) {
13 | System.out.println("main Thread is interrupted");
14 | }
15 |
16 | for (int i = 1; i <= 4; i++) {
17 | System.out.println("main Thread Execution - " + i);
18 | }
19 | }
20 | }
21 |
22 | class ChildThread extends Thread {
23 |
24 | private static Thread parentThreadRef;
25 |
26 | public ChildThread(Thread parentThreadRef) {
27 | this.parentThreadRef = parentThreadRef;
28 | }
29 |
30 | public void run() {
31 | parentThreadRef.interrupt();
32 | for (int i = 1; i <= 4; i++) {
33 | System.out.println("Child Thread Execution - " + i);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/ThreadPriorityDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency;
2 |
3 | public class ThreadPriorityDemo {
4 | public static void main(String[] args) {
5 | // Creating child tasks
6 | ChildTask childTask1 = new ChildTask();
7 | ChildTask childTask2 = new ChildTask();
8 |
9 | // Start Child Threads
10 | new Thread(childTask1).start();
11 | new Thread(childTask2).start();
12 |
13 | System.out.println(Thread.currentThread().getName() + " executed by main thread");
14 | }
15 | }
16 |
17 | class ChildTask implements Runnable {
18 | public void run()
19 | {
20 | System.out.println(Thread.currentThread().getName() + " executed by child thread");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/interview/DoNotOverrideRunMethod.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency.interview;
2 |
3 | public class DoNotOverrideRunMethod {
4 |
5 | public static void main(String[] args) {
6 | SubTask subtask = new SubTask();
7 | subtask.start();
8 | }
9 | }
10 |
11 | class SubTask extends Thread { }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/interview/OverrideStartMethod.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency.interview;
2 |
3 | public class OverrideStartMethod {
4 |
5 | public static void main(String[] args) {
6 | ChildThread childThread = new ChildThread();
7 | childThread.start();
8 | }
9 |
10 | }
11 |
12 | class ChildThread extends Thread {
13 |
14 | public void start() {
15 | super.start();
16 | System.out.println("Overriding start() method in ChildThread");
17 | }
18 |
19 | public void run(){
20 | System.out.println("ChildThread run() method");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/interview/ThreadGroupExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency.interview;
2 |
3 | public class ThreadGroupExample {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(Thread.currentThread().getThreadGroup().getName());
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/threaddumps/ThreadHighCPU.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency.threaddumps;
2 |
3 | public class ThreadHighCPU {
4 |
5 | public static void main(String[] args) {
6 | // Create a CPU-intensive task and run it in a separate thread
7 | Runnable cpuIntensiveTask = () -> {
8 | while (true) {
9 | // Simulate a CPU-intensive operation (e.g., busy-wait loop)
10 | double result = 0;
11 | for (int i = 0; i < 1000000; i++) {
12 | result += Math.random();
13 | }
14 | }
15 | };
16 |
17 | Thread thread = new Thread(cpuIntensiveTask);
18 | thread.start();
19 |
20 | // Let the CPU-intensive task run for a while (you may need to manually terminate it)
21 | try {
22 | Thread.sleep(60000); // Run for 60 seconds
23 | } catch (InterruptedException e) {
24 | e.printStackTrace();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/concurrency/virtualThreads/ExecutorExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.concurrency.virtualThreads;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.concurrent.ExecutorService;
6 | import java.util.concurrent.Executors;
7 | import java.util.concurrent.TimeUnit;
8 |
9 | public class ExecutorExample {
10 |
11 | void main(String[] args) throws InterruptedException {
12 |
13 | List numList = Arrays.asList(1, 2, 3, 4, 5);
14 |
15 | ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
16 |
17 | numList.forEach(num ->
18 | executor.execute(() -> {
19 | System.out.println(STR."Square of \{num} is :: \{square(num)}");
20 | })
21 | );
22 |
23 | executor.awaitTermination(2, TimeUnit.SECONDS);
24 | executor.shutdown();
25 | }
26 |
27 | private Integer square(Integer num) {
28 | return num * num;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ArrayCopy.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 |
5 | public class ArrayCopy
6 | {
7 | public static void main(String[] args)
8 | {
9 | String[] names = {"Alex", "Brian", "Charles", "David"};
10 |
11 | System.out.println(Arrays.toString(names)); //[Alex, Brian, Charles, David]
12 |
13 | String[] cloneOfNames = names.clone();
14 |
15 | System.out.println(Arrays.toString(cloneOfNames)); //[Alex, Brian, Charles, David]
16 |
17 | String[] copyOfNames = Arrays.copyOf(names, names.length);
18 |
19 | System.out.println(Arrays.toString(copyOfNames)); //[Alex, Brian, Charles, David]
20 |
21 | String[] copyOfNames2 = new String[names.length];
22 | System.arraycopy(names, 0, copyOfNames2, 0, copyOfNames2.length);
23 |
24 | System.out.println(Arrays.toString(copyOfNames2)); //[Alex, Brian, Charles, David]
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ArrayCopyRange.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | public class ArrayCopyRange {
7 | public static void main(String[] args) {
8 | String[] names = {"Alex", "Brian", "Charles", "David"};
9 |
10 | //Sub array from index '0' (inclusive) to index '2' (exclusive)
11 | String[] partialNames = Arrays.copyOfRange(names, 0, 2);
12 | // [Alex, Brian]
13 |
14 | System.out.println(Arrays.toString(partialNames));
15 |
16 | //Sub array to list
17 | List namesList = Arrays.asList(Arrays.copyOfRange(names, 2, names.length));
18 | // [Charles, David]
19 |
20 | System.out.println(namesList);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ArrayExceptions.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | public class ArrayExceptions {
4 | public static void main(final String[] args)
5 | {
6 | //1
7 | Number[] numbers = new Number[3];
8 | numbers[0] = Integer.valueOf(10); // Works Fine.
9 |
10 | //2
11 | Integer[] intArray = { 1, 2, 3, 4 };
12 | Number[] numArray = intArray;
13 | numArray[0] = 10; // Works Fine.
14 |
15 | double value = 10.01;
16 |
17 | if(intArray.getClass().getComponentType()
18 | == ((Object)value).getClass()) {
19 | numArray[0] = value;
20 | } else {
21 | System.out.println("Incompitable type");
22 | }
23 |
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ArrayListToArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 |
6 | public class ArrayListToArray {
7 | public static void main(final String[] args) {
8 | ArrayList listOfIntegers = new ArrayList<>();
9 | listOfIntegers.add(1);
10 | listOfIntegers.add(2);
11 | listOfIntegers.add(3);
12 |
13 | System.out.println(listOfIntegers);
14 |
15 | int[] intArray = listOfIntegers.stream()
16 | .mapToInt(Integer::intValue)
17 | .toArray();
18 |
19 | System.out.println(Arrays.toString(intArray));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ConvertBetweenArrayAndStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.stream.IntStream;
5 | import java.util.stream.Stream;
6 |
7 |
8 | public class ConvertBetweenArrayAndStream {
9 | public static void main(final String[] args) {
10 | int[] primitiveArray = {0,1,2,3,4};
11 | String[] stringArray = {"a", "b", "c", "d", "e"};
12 |
13 | //1. Array -> Stream
14 | Stream strStream = Arrays.stream(stringArray);
15 | IntStream intStream = Arrays.stream(primitiveArray);
16 | Stream integerStream = Arrays.stream(primitiveArray).boxed();
17 |
18 | //2.Stream -> Array
19 | stringArray = strStream.toArray(String[]::new);
20 | primitiveArray = intStream.toArray();
21 | primitiveArray = integerStream.mapToInt(i -> i).toArray();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ConvertBetweenPrimitiveAndObjects.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import org.apache.commons.lang3.ArrayUtils;
4 |
5 | import java.util.Arrays;
6 |
7 | public class ConvertBetweenPrimitiveAndObjects {
8 | public static void main(String[] args) {
9 | int[] primitiveArray = new int[]{0, 1, 2, 3, 4, 5};
10 | Integer[] objectArray = new Integer[]{0, 1, 2, 3, 4, 5};
11 |
12 | //1.Primitive array to object array
13 | Integer[] outputArray1 = Arrays.stream(primitiveArray)
14 | .boxed()
15 | .toArray(Integer[]::new);
16 |
17 | System.out.println(Arrays.toString(outputArray1));
18 |
19 | Integer[] outputArray2 = ArrayUtils.toObject(primitiveArray);
20 |
21 | System.out.println(Arrays.toString(outputArray2));
22 |
23 | //2. Object array to primitive array
24 | int[] outputArray3 = Arrays.stream(objectArray)
25 | .mapToInt(Integer::intValue)
26 | .toArray();
27 |
28 | System.out.println(Arrays.toString(outputArray3));
29 |
30 | int[] outputArray4 = ArrayUtils.toPrimitive(objectArray);
31 |
32 | System.out.println(Arrays.toString(outputArray4));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ConvertPrimitiveArrayToList.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import com.google.common.primitives.Ints;
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 | import java.util.List;
7 | import java.util.stream.Collectors;
8 | import java.util.stream.IntStream;
9 | import org.apache.commons.lang3.ArrayUtils;
10 |
11 | public class ConvertPrimitiveArrayToList {
12 |
13 | public static void main(String[] args) {
14 |
15 | /*List list = Arrays.asList(new Integer[]{1,2,3,4}); //Works!
16 |
17 | List list1 = Arrays.asList(new int[]{1,2,3,4}); //Does not work!*/
18 |
19 | int[] intArray = new int[]{0, 1, 2, 3, 4, 5};
20 |
21 | //1 - Stream
22 | List list1 = IntStream.of(intArray).boxed().toList();
23 |
24 | //2 - Guava
25 | List list2 = Ints.asList(intArray);
26 |
27 | //3 - Commons Lang3
28 | List list3 = Arrays.asList(ArrayUtils.toObject(intArray));
29 |
30 | //4 - Iteration
31 | List list4 = new ArrayList();
32 | for (int value : intArray) {
33 | list4.add(value);
34 | }
35 |
36 | //5
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ConvertStringArrayToIntArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 |
5 | public class ConvertStringArrayToIntArray {
6 |
7 | public static void main(String[] args) {
8 | String[] strArray = new String[]{"1", "2", "3"};
9 |
10 | //1
11 | int[] intArray = Arrays.stream(strArray)
12 | .mapToInt(Integer::parseInt)
13 | .toArray();
14 |
15 | System.out.println(Arrays.toString(intArray));
16 |
17 | Integer[] integerArray = Arrays.stream(strArray)
18 | .map(Integer::parseInt)
19 | .toArray(Integer[]::new);
20 |
21 | System.out.println(Arrays.toString(integerArray));
22 |
23 | //2
24 | String[] invalidStrArray = new String[]{"1", "2", "3", "four", "5"};
25 | int[] intArray1 = Arrays.stream(invalidStrArray).mapToInt(str -> {
26 | try {
27 | return Integer.parseInt(str);
28 | } catch (NumberFormatException nfe) {
29 | return -1;
30 | }
31 | }).toArray();
32 |
33 | System.out.println(Arrays.toString(intArray1));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/Intersection.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 | import org.junit.jupiter.api.Assertions;
7 |
8 | public class Intersection {
9 |
10 | public static void main(String[] args) {
11 | Integer[] array1 = new Integer[]{1, 2, 3, 4, 5};
12 | Integer[] array2 = new Integer[]{4, 5, 6, 7};
13 |
14 | //1
15 |
16 | HashSet set = new HashSet<>();
17 | set.addAll(Arrays.asList(array1));
18 | set.retainAll(Arrays.asList(array2));
19 |
20 | Assertions.assertEquals(Set.of(4, 5), set);
21 |
22 | //convert to array, if needed
23 | Integer[] intersection = set.toArray(new Integer[0]);
24 |
25 | Assertions.assertArrayEquals(new Integer[]{4, 5}, intersection);
26 |
27 | //2
28 |
29 | intersection = Arrays.stream(array1)
30 | .distinct()
31 | .filter(x -> Arrays.asList(array2).contains(x))
32 | .toArray(Integer[]::new);
33 |
34 | Assertions.assertArrayEquals(new Integer[]{4, 5}, intersection);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/JoinArrayItems.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.StringJoiner;
6 | import java.util.stream.Collectors;
7 |
8 | @SuppressWarnings("unused")
9 | public class JoinArrayItems {
10 | public static void main(final String[] args) {
11 | int[] intArray = {};
12 | String[] strArray = { "a", "b", "c" };
13 | String joined2 = String.join(",", strArray);
14 |
15 | StringJoiner joiner = new StringJoiner(", ", "[", "]");
16 |
17 | String joinedString = joiner.add("How")
18 | .add("To")
19 | .add("Do")
20 | .add("In")
21 | .add("Java")
22 | .toString();
23 |
24 | System.out.println(joinedString); // [How, To, Do, In, Java]
25 |
26 | List tokens = Arrays.asList("How", "To", "Do", "In", "Java");
27 |
28 |
29 | joinedString = tokens.stream()
30 | .collect(Collectors.joining(", ", "[", "]"));
31 |
32 | System.out.println(joinedString);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/Print2dArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 |
5 | public class Print2dArray
6 | {
7 | public static void main(String[] args)
8 | {
9 | int [][] cordinates = { {1,2}, {2,4}, {3,6,9} };
10 |
11 | System.out.println( Arrays.deepToString( cordinates ) );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ResizeArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 |
6 | public class ResizeArray {
7 | public static void main(String[] args) {
8 | String[] originalArray = {"A", "B", "C", "D", "E"};
9 |
10 | //1
11 | String[] resizedArray = Arrays.copyOf(originalArray, 10);
12 | resizedArray[5] = "F";
13 | System.out.println(Arrays.toString(resizedArray));
14 |
15 | //2
16 | ArrayList list = new ArrayList<>(Arrays.asList(originalArray));
17 | list.add("F");
18 | System.out.println(list);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/ReverseArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import org.apache.commons.lang3.ArrayUtils;
4 |
5 | import java.util.Arrays;
6 | import java.util.Collections;
7 | import java.util.stream.IntStream;
8 |
9 | public class ReverseArray {
10 | public static void main(final String[] args) {
11 | // 1
12 | String[] array = {"A", "B", "C", "D", "E"};
13 | Collections.reverse(Arrays.asList(array));
14 | System.out.println(Arrays.toString(array));
15 |
16 | // 2
17 | array = new String[]{"A", "B", "C", "D", "E"};
18 | for (int i = 0; i < array.length / 2; i++) {
19 | String temp = array[i];
20 | array[i] = array[array.length - 1 - i];
21 | array[array.length - 1 - i] = temp;
22 | }
23 | System.out.println(Arrays.toString(array));
24 |
25 | final String[] arr = {"A", "B", "C", "D", "E"};
26 | Object[] reversedArr = IntStream.rangeClosed(1, array.length)
27 | .mapToObj(i -> arr[arr.length - i])
28 | .toArray();
29 | System.out.println(Arrays.toString(reversedArr));
30 |
31 | //3
32 | ArrayUtils.reverse(arr);
33 | System.out.println(Arrays.toString(arr));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/SortStringAlphabetically.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | public class SortStringAlphabetically {
4 |
5 | public static void main(String[] args) {
6 | String string = "adcbgekhs";
7 |
8 | String sortedString = sortWithArray(string);
9 |
10 | System.out.println(sortedString);
11 | }
12 |
13 | static String sortWithArray(String str) {
14 | char arr[] = str.toCharArray();
15 | char temp;
16 |
17 | int i = 0;
18 | while (i < arr.length) {
19 | int j = i + 1;
20 | while (j < arr.length) {
21 | if (arr[j] < arr[i]) {
22 | temp = arr[i];
23 | arr[i] = arr[j];
24 | arr[j] = temp;
25 | }
26 | j += 1;
27 | }
28 | i += 1;
29 | }
30 | return String.copyValueOf(arr);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/Union.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 | import java.util.stream.Stream;
7 | import org.junit.jupiter.api.Assertions;
8 |
9 | public class Union {
10 |
11 | public static void main(String[] args) {
12 | Integer[] arr1 = {0, 2};
13 | Integer[] arr2 = {1, 3};
14 |
15 | HashSet set = new HashSet<>();
16 |
17 | set.addAll(Arrays.asList(arr1));
18 | set.addAll(Arrays.asList(arr2));
19 |
20 | Assertions.assertEquals(Set.of(0, 1, 2, 3), set);
21 |
22 | //convert to array, if needed
23 | Integer[] union = set.toArray(new Integer[0]);
24 |
25 | Assertions.assertArrayEquals(new Integer[]{0, 1, 2, 3}, union);
26 |
27 | //2
28 |
29 | union = Stream.of(arr1, arr2).flatMap(Stream::of).toArray(Integer[]::new);
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/array/User.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.array;
2 |
3 | public class User implements Comparable {
4 |
5 | public long id;
6 | public String firstName;
7 | public String lastName;
8 |
9 | public long getId() {
10 | return id;
11 | }
12 |
13 | public void setId(final long id) {
14 | this.id = id;
15 | }
16 |
17 | public String getFirstName() {
18 | return firstName;
19 | }
20 |
21 | public void setFirstName(final String firstName) {
22 | this.firstName = firstName;
23 | }
24 |
25 | public String getLastName() {
26 | return lastName;
27 | }
28 |
29 | public void setLastName(final String lastName) {
30 | this.lastName = lastName;
31 | }
32 |
33 | @Override
34 | public String toString() {
35 | return "Employee [id=" + id + ", firstName=" + firstName + ", lastName="
36 | + lastName + "]";
37 | }
38 |
39 | @Override
40 | public int compareTo(final User user) {
41 | if(user == null ) {
42 | return -1;
43 | } else {
44 | return (int)(this.id - user.id);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/AllPrimeFactors.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class AllPrimeFactors {
7 |
8 | public static void main(String[] args) {
9 | System.out.println(primeFactors(90));
10 | System.out.println(primeFactors(190));
11 | System.out.println(primeFactors(350));
12 | }
13 |
14 | public static List primeFactors(int v) {
15 | List factorsList = new ArrayList<>();
16 | int s = 2;
17 |
18 | while (v > 1) {
19 | // each perfect division give us a prime factor
20 | if (v % s == 0) {
21 | factorsList.add(s);
22 | v = v / s;
23 | } else {
24 | s++;
25 | }
26 | }
27 |
28 | return factorsList;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/AssertExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class AssertExample {
4 |
5 | public static void main(String[] args) {
6 | Person person = new Person(1L, "Lokesh", 40);
7 |
8 | //Passes successfully
9 | assert person.age() >= 18 : "Age is less than 18";
10 |
11 | Person person1 = new Person(1L, "Lokesh", 14);
12 |
13 | //Failed
14 | assert person1.age() >= 18 : "Age is less than 18";
15 |
16 | System.out.println("Done");
17 | }
18 | }
19 |
20 | record Person(Long id, String name, int age) {
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/BusinessCustomer.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class BusinessCustomer extends Customer
4 | {
5 | private String legalName;
6 |
7 | public String getLegalName() {
8 | return legalName;
9 | }
10 |
11 | public void setLegalName(String legalName) {
12 | this.legalName = legalName;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/CharacterEncodingExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.nio.charset.Charset;
4 |
5 | public class CharacterEncodingExample {
6 |
7 | public static void main(String[] args) {
8 | String fileCoding = System.getProperty("file.encoding");
9 | System.out.println(STR."Default Character Encoding: \{fileCoding}");
10 |
11 | String filePathEncoding = System.getProperty("sun.jnu.encoding");
12 | System.out.println(STR."Default File Path Encoding: \{filePathEncoding}");
13 |
14 | String defaultCharset = Charset.defaultCharset().displayName();
15 | System.out.println(STR."Default Charset Name: \{defaultCharset}");
16 |
17 | /*System.setProperty("file.encoding", "UTF-16");
18 | System.setProperty("sun.jnu.encoding", "UTF-16");*/
19 |
20 | defaultCharset = System.out.charset().displayName();
21 | System.out.println(STR."Default Character Encoding: \{defaultCharset}");
22 |
23 | System.out.println("The façade pattern is a software-design pattern.");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/Customer.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public abstract class Customer {
4 |
5 | private Long id;
6 |
7 | public Long getId() {
8 | return id;
9 | }
10 |
11 | public void setId(Long id) {
12 | this.id = id;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/ForEachExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import java.util.function.Consumer;
7 |
8 | public class ForEachExamples {
9 |
10 | public static void main(String[] args) {
11 | List list = Arrays.asList("A","B","C","D");
12 | ArrayList arrayList = new ArrayList<>(list);
13 |
14 | //1
15 | list.forEach(System.out::println);
16 |
17 | //2
18 | Consumer action = x -> System.out.println(x.toLowerCase());
19 | list.forEach(action);
20 |
21 | list.forEach(e -> System.out.println(e.toLowerCase()));
22 |
23 | //3
24 | list.forEach(e -> {
25 | System.out.println(e.toLowerCase());
26 | //other statements
27 | });
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/ForLoopExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class ForLoopExample {
4 |
5 | public static void main(String[] args) {
6 |
7 | int[] array = new int[]{0, 1, 2, 3, 4, 5};
8 |
9 | for (int i = 0; i < array.length; i++) {
10 | System.out.format("The value at index location %d is %d \n", i, array[i]);
11 | }
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/HelpfulNullPointerExceptionExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class HelpfulNullPointerExceptionExample
4 | {
5 | @SuppressWarnings("null")
6 | public static void main(String[] args)
7 | {
8 | Employee e = null;
9 |
10 | System.out.println(e.getName());
11 | }
12 | }
13 |
14 | class Employee {
15 | Long id;
16 | String name;
17 |
18 | public Long getId() {
19 | return id;
20 | }
21 | public void setId(Long id) {
22 | this.id = id;
23 | }
24 | public String getName() {
25 | return name;
26 | }
27 | public void setName(String name) {
28 | this.name = name;
29 | }
30 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/MainClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class MainClass
4 | {
5 | public static void main(String[] args)
6 | {
7 | System.out.println("Hello, World!");
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/ObjectIdentityString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.util.Objects;
4 | import lombok.AllArgsConstructor;
5 |
6 | public class ObjectIdentityString {
7 |
8 | public static void main(String[] args) {
9 | Record record = new Record(1L, "record name");
10 |
11 | System.out.println(record);
12 |
13 | System.out.println(record != null ? Objects.toIdentityString(record) : "null");
14 |
15 | System.out.println(getIdentityString(record));
16 | }
17 |
18 | static String getIdentityString(Object object) {
19 | return object.getClass().getName() + "@"
20 | + Integer.toHexString(System.identityHashCode(object));
21 | }
22 | }
23 |
24 | @AllArgsConstructor
25 | class Record {
26 | long id;
27 | String name;
28 |
29 | @Override
30 | public String toString() {
31 | return STR."Record{id=\{id}, name='\{name}\{'\''}\{'}'}";
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/PersonalCustomer.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class PersonalCustomer extends Customer {
4 |
5 | private String firstName;
6 | private String middleName;
7 | private String lastName;
8 |
9 | public String getFirstName() {
10 | return firstName;
11 | }
12 |
13 | public void setFirstName(String firstName) {
14 | this.firstName = firstName;
15 | }
16 |
17 | public String getMiddleName() {
18 | return middleName;
19 | }
20 |
21 | public void setMiddleName(String middleName) {
22 | this.middleName = middleName;
23 | }
24 |
25 | public String getLastName() {
26 | return lastName;
27 | }
28 |
29 | public void setLastName(String lastName) {
30 | this.lastName = lastName;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | 1. [Java 14 - switch expression](https://howtodoinjava.com/java14/switch-expressions/)
4 | 2. [Java 14 - yield keyword](https://howtodoinjava.com/java14/yield-keyword-in-java/)
5 | 3. [Java 14 - Better NullPointerException](https://howtodoinjava.com/java14/helpful-nullpointerexception/)
6 | 4. [Java 14 - Text blocks and best practices](https://howtodoinjava.com/java14/java-text-blocks/)
7 | 5. [Java 14 - record type](https://howtodoinjava.com/java14/java-14-record-type/)
8 | 6. [Java 14 - Pattern Matching for instanceof](https://howtodoinjava.com/java14/pattern-matching-instanceof/)
9 | 7. [Java While Loop](https://howtodoinjava.com/java/basics/while-loop-in-java/)
10 | 8. [Java String substring()](https://howtodoinjava.com/java/string/java-string-substring-example/)
11 | 9. [Printf-Style Output Formatting in Java](https://howtodoinjava.com/java/basics/printf-style-output-formatting/)
12 | 10. [Java – Round Off Double or Float Values to 2 Decimal Places](https://howtodoinjava.com/java/basics/round-off-n-decimal-places/)
13 | 11. [Builder Pattern for Java Records](https://howtodoinjava.com/java/basics/builder-pattern-for-java-records/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/RegexExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.util.regex.Pattern;
4 |
5 | public class RegexExamples {
6 | public static void main(String[] args)
7 | {
8 | System.out.println(Pattern.compile(".*").matcher("abcd").matches()); //true
9 | System.out.println(Pattern.compile("[a-zA-Z]*").matcher("abcd").matches()); //true
10 | System.out.println(Pattern.compile("[0-9]*").matcher("01234").matches()); //true
11 | System.out.println(Pattern.compile("[a-zA-Z0-9]*").matcher("a1b2c3").matches()); //true
12 | }
13 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/StricfpExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class StricfpExample {
4 |
5 | public static void main(String[] args) {
6 | runMethod();
7 | }
8 |
9 | strictfp public static void runMethod() {
10 | double x = 5.899999;
11 | double y = 13.888345;
12 | double z = 14.463534545;
13 |
14 | double m1 = (x * y) * z; // 1185.1596894396725
15 | double m2 = (x * (y * z)); // 1185.1596894396728
16 |
17 | System.out.println(m1);
18 | System.out.println(m2);
19 |
20 | System.out.println(m1 == m2); //false
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/StringPoolExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class StringPoolExample
4 | {
5 | public static void main(String[] args)
6 | {
7 | String a = "howtodoinjava";
8 | String b = "howtodoinjava";
9 |
10 | String c = new String("howtodoinjava");
11 | String d = c.intern();
12 |
13 | System.out.println(a == b); //true
14 | System.out.println(b == c); //false
15 |
16 | System.out.println(a == c); //false
17 | System.out.println(a == d); //true
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/SwitchStatement.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class SwitchStatement
4 | {
5 | public static void main(String[] args)
6 | {
7 | System.out.println("Monday is : " + isWeekDay(Day.TUE));
8 | System.out.println("Monday is : " + isWeekDay(Day.SUN));
9 | }
10 |
11 | public static Boolean isWeekDay(Day day)
12 | {
13 | Boolean result = switch(day) {
14 | case MON, TUE, WED, THUR, FRI -> {
15 | System.out.println("It's Weekday");
16 | yield true;
17 | }
18 | case SAT, SUN -> {
19 | System.out.println("It's Weekend");
20 | yield false;
21 | }
22 | default -> throw new IllegalArgumentException("Invalid day: " + day.name());
23 | };
24 | return result;
25 | }
26 | }
27 |
28 | enum Day {
29 | MON, TUE, WED, THUR, FRI, SAT, SUN
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/TextBlocks.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class TextBlocks
4 | {
5 | public static void main(String[] args)
6 | {
7 | String dbSchema = """
8 | CREATE TABLE 'TEST'.'EMPLOYEE' \s
9 | ( \s
10 | 'ID' INT NOT NULL DEFAULT 0 , \s
11 | 'FIRST_NAME' VARCHAR(100) NOT NULL , \s
12 | 'LAST_NAME' VARCHAR(100) NULL , \s
13 | 'STAT_CD' TINYINT NOT NULL DEFAULT 0 \s
14 | ); \s
15 | """;
16 |
17 | System.out.println(dbSchema.replace("\s", "."));
18 |
19 | String string = "Hello";
20 | String textBlock = """
21 | World
22 | !! """;
23 |
24 | String joinedString = string + textBlock;
25 |
26 | joinedString = joinedString.replace("\n", System.lineSeparator());
27 |
28 | System.out.println(joinedString);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/UnderscoreInLiterals.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | public class UnderscoreInLiterals {
4 |
5 | public static void main(String[] args) {
6 |
7 | //Supported in byte
8 | byte improvedByte = 0b0010_0101;
9 |
10 | //Supported in int
11 | int improvedInt = 10_00_000;
12 |
13 | //Supported in long
14 | long improvedLong = 10_00_000l;
15 |
16 | //Supported in float
17 | float improvedFloat = 10_00_000.16f;
18 |
19 | //Supported in double
20 | double improvedDouble = 10_00_000.56d;
21 |
22 | System.out.println(improvedByte); //37
23 | System.out.println(improvedInt); //1000000
24 | System.out.println(improvedLong); //1000000
25 | System.out.println(improvedFloat); //1000000.2
26 | System.out.println(improvedDouble); //1000000.56
27 |
28 | //NOT ALLOWED
29 |
30 | /*//adjacent to decimal point
31 | float value = 10_.12F;
32 | float value1 = 10._12F;
33 |
34 | //adjacent to F or L
35 | float value2 = 10.12F_;
36 | float value3 = 10_.12_F;
37 |
38 | //at start or end
39 | int value = 10_;
40 | int value = _10;*/
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/WhileLoopExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Iterator;
5 |
6 | public class WhileLoopExample {
7 |
8 | public static void main(String[] args)
9 | {
10 | //1
11 | int counter = 1;
12 | while (counter <= 5)
13 | {
14 | System.out.println(counter);
15 | counter++;
16 | }
17 |
18 | //2
19 | ArrayList list = new ArrayList<>();
20 |
21 | list.add(1);
22 | list.add(2);
23 | list.add(3);
24 |
25 | Iterator iterator = list.iterator();
26 |
27 | while (iterator.hasNext())
28 | {
29 | System.out.println(iterator.next());
30 | }
31 |
32 | //3
33 | Integer[] idArray = new Integer[] {1,2,3,4,5};
34 | int index = 0;
35 | while (index < idArray.length)
36 | {
37 | System.out.println(idArray[index]);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/math/MathAbsoluteExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic.math;
2 |
3 | public class MathAbsoluteExamples {
4 |
5 | public static void main(String[] args) {
6 |
7 | double doubleValue = -10.56;
8 | float floatValue = -7.8f;
9 | int intValue = -15;
10 | long longValue = -123456789L;
11 |
12 | System.out.println(STR."Absolute value of double: \{Math.abs(doubleValue)}");
13 | System.out.println(STR."Absolute value of float: \{Math.abs(floatValue)}");
14 | System.out.println(STR."Absolute value of int: \{Math.abs(intValue)}");
15 | System.out.println(STR."Absolute value of long: \{Math.abs(longValue)}");
16 |
17 | //Overflow / Underflow Issue
18 |
19 | int intMinValue = Integer.MIN_VALUE;
20 | long longMinValue = Long.MIN_VALUE;
21 |
22 | System.out.println(STR."Absolute value of int: \{Math.abs(intMinValue)}");
23 | System.out.println(STR."Absolute value of long: \{Math.abs(longMinValue)}");
24 |
25 | System.out.println(STR."Absolute value of int: \{Math.absExact(intMinValue)}");
26 | System.out.println(STR."Absolute value of long: \{Math.absExact(longMinValue)}");
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/math/MathDivideExact.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic.math;
2 |
3 | import java.util.function.BinaryOperator;
4 |
5 | public class MathDivideExact {
6 |
7 | public static void main(String[] args) {
8 |
9 | int result = 100 / -1;
10 | System.out.println(result);
11 |
12 | System.out.println(Integer.MAX_VALUE);
13 | int x = Integer.MIN_VALUE;
14 | System.out.println(x);
15 | int quotient1 = x/-1; // -2,147,483,648
16 | System.out.println(quotient1);
17 |
18 | long y = Integer.MIN_VALUE;
19 | long quotient2 = y/-1; // 2,147,483,648
20 | System.out.println(quotient2);
21 |
22 | int quotientExactFine = Math.divideExact(4, -1);
23 | System.out.println(quotientExactFine);
24 |
25 | int quotientExactEx = Math.divideExact(x, -1);
26 | System.out.println(quotientExactEx);
27 |
28 | BinaryOperator operator = Math::divideExact;
29 | int quotientExactBo = operator.apply(x, -1);
30 | System.out.println(quotientExactBo);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/math/MathFloorDivCeilDiv.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic.math;
2 |
3 | public class MathFloorDivCeilDiv {
4 |
5 | public static void main(String[] args) {
6 |
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/record/Employee.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic.record;
2 |
3 | import java.io.Serializable;
4 | import java.util.Objects;
5 |
6 | public record Employee(Long id, String firstName, String lastName, String email, int age)
7 | implements Serializable {
8 |
9 | static boolean minor;
10 |
11 | public boolean isMinor() {
12 | return minor;
13 | }
14 |
15 | public String fullName() {
16 | return firstName + " " + lastName;
17 | }
18 |
19 | /*public Employee {
20 | if (age < 18) {
21 | //minor = true;
22 | throw new IllegalArgumentException("You cannot hire a minor person as employee");
23 | }
24 | }
25 | */
26 | public Employee {
27 | Objects.requireNonNull(id);
28 | Objects.requireNonNull(email);
29 |
30 | if (age < 18) {
31 | throw new IllegalArgumentException("You cannot hire a minor person as employee");
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/basic/record/GenericRecordExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.basic.record;
2 |
3 | public class GenericRecordExample {
4 |
5 | public static void main(String[] args) {
6 | Container intContainer = new Container<>(1, Integer.valueOf(1));
7 | Container stringContainer = new Container<>(1, "1");
8 |
9 | Integer intValue = intContainer.value();
10 | String strValue = stringContainer.value();
11 |
12 |
13 | }
14 | }
15 |
16 | record Container(int id, T value) {
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/AddMultipleItems.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections;
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 AddMultipleItems
9 | {
10 | public static void main(final String[] args)
11 | {
12 | ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b"));
13 |
14 | Collections.addAll(arrayList, "c", "d");
15 |
16 | System.out.println(arrayList);
17 |
18 | //List 1
19 | List namesList = Arrays.asList( "a", "b", "c");
20 |
21 | ArrayList instance = new ArrayList<>(namesList);
22 |
23 | System.out.println(instance);
24 |
25 | //List 2
26 | ArrayList otherList = new ArrayList<>(Arrays.asList( "d", "e"));
27 |
28 | //Do not add 'a' to the new list
29 | namesList.stream()
30 | .filter(name -> !"a".equals(name))
31 | .forEachOrdered(otherList::add);
32 |
33 | System.out.println(otherList);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/ArrayListToLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections;
2 |
3 | import java.util.ArrayList;
4 | import java.util.LinkedList;
5 | import org.junit.jupiter.api.Assertions;
6 |
7 | public class ArrayListToLinkedList {
8 |
9 | public static void main(String[] args) {
10 | LinkedList linkedList = new LinkedList();
11 |
12 | //1.1.
13 | //add items
14 | linkedList.add("A");
15 | linkedList.add("B");
16 | linkedList.add("C");
17 | linkedList.add("D");
18 |
19 | ArrayList arrayList = new ArrayList<>(linkedList);
20 |
21 | Assertions.assertEquals(4, arrayList.size());
22 |
23 | //1.2
24 | ArrayList arrayList1 = new ArrayList<>();
25 | arrayList1.addAll(linkedList);
26 |
27 | Assertions.assertEquals(4, arrayList1.size());
28 |
29 | //2
30 | LinkedList linkedList1 = new LinkedList(arrayList);
31 |
32 | Assertions.assertEquals(4, linkedList1.size());
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/AlternateNextAndPrevious.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.ListIterator;
6 |
7 | public class AlternateNextAndPrevious {
8 |
9 | public static void main(String[] args) {
10 |
11 | List numbers = new ArrayList<>();
12 |
13 | for (int i = 1; i <= 5; i++) { numbers.add(i); }
14 |
15 | ListIterator iterator = numbers.listIterator();
16 |
17 | System.out.println(iterator.next()); //1
18 |
19 | System.out.println(iterator.next()); //2
20 |
21 | System.out.println(iterator.previous()); //2
22 |
23 | System.out.println(iterator.next()); //2
24 |
25 | System.out.println(iterator.previous()); //2
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/ConcurrentModification.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.ArrayList;
4 | import java.util.ConcurrentModificationException;
5 | import java.util.List;
6 | import java.util.ListIterator;
7 |
8 | public class ConcurrentModification {
9 |
10 | public static void main(String[] args) {
11 |
12 | try {
13 |
14 | List numbers = new ArrayList<>();
15 |
16 | for (int i = 1; i <= 5; i++) { numbers.add(i); }
17 |
18 | ListIterator iterator = numbers.listIterator();
19 |
20 | System.out.println(iterator.next());
21 |
22 | numbers.add(0, 10);
23 |
24 | System.out.println(iterator.next());
25 |
26 | } catch (ConcurrentModificationException exception) {
27 |
28 | System.out.println("Attempted to the modify collection");
29 |
30 | System.out.println(exception);
31 |
32 | }
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/EnumerationCursor.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.Enumeration;
4 | import java.util.Vector;
5 |
6 | public class EnumerationCursor {
7 |
8 | public static void main(String[] args) {
9 |
10 | Vector vector = new Vector<>();
11 |
12 | for(int i=1;i<=10;i++){ vector.addElement(i); }
13 |
14 | Enumeration enumeration = vector.elements();
15 |
16 | while(enumeration.hasMoreElements()){
17 |
18 | System.out.print(enumeration.nextElement() + " ");
19 |
20 | }
21 |
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/IteratorCursor.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.*;
4 |
5 | public class IteratorCursor {
6 |
7 | public static void main(String[] args) {
8 |
9 | Set immutableSet = Set.of(1,2,3,4,5,6,7,8,9,10); // Immutable Set
10 | Set elements = new HashSet<>(immutableSet); // Mutable Set
11 |
12 | Iterator iterator = elements.iterator();
13 |
14 | int num;
15 |
16 | while (iterator.hasNext()){
17 |
18 | if ((num = iterator.next()) == 5){ iterator.remove(); }
19 |
20 | else { System.out.print(num + " "); }
21 | }
22 |
23 | System.out.println("\n"+elements);
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/SpliteratorCursor.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.List;
4 | import java.util.Spliterator;
5 | import java.util.stream.Stream;
6 |
7 | public class SpliteratorCursor {
8 |
9 | public static void main(String[] args) {
10 |
11 | List big = Stream.generate(() -> "Hello").limit(30000).toList();
12 |
13 | Spliterator split = big.spliterator(); // 30000
14 |
15 | System.out.println(split.estimateSize());
16 |
17 | Spliterator split1 = split.trySplit();
18 |
19 | System.out.println(split.estimateSize()); // 15000
20 |
21 | System.out.println(split1.estimateSize()); // 15000
22 |
23 | new Thread(() -> split.forEachRemaining(elem -> System.out.println("TH1 " + elem))).start();
24 |
25 | new Thread(() -> split1.forEachRemaining(elem -> System.out.println("TH2 " + elem))).start();
26 |
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/cursors/SpliteratorEstimateSize.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.cursors;
2 |
3 | import java.util.List;
4 | import java.util.Spliterator;
5 | import java.util.stream.Stream;
6 |
7 | public class SpliteratorEstimateSize {
8 |
9 | public static void main(String[] args) {
10 |
11 | List big = Stream.generate(() -> "Hello").limit(10).toList();
12 |
13 | Spliterator split = big.spliterator();
14 |
15 | split.tryAdvance(System.out::println);
16 | split.tryAdvance(System.out::println);
17 | split.tryAdvance(System.out::println);
18 | split.tryAdvance(System.out::println);
19 | split.tryAdvance(System.out::println);
20 |
21 | System.out.println(split.estimateSize());
22 |
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/AddItem.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 | import org.apache.commons.collections4.CollectionUtils;
7 | import org.junit.jupiter.api.Assertions;
8 |
9 | public class AddItem {
10 |
11 | public static void main(String[] args) {
12 |
13 | //1
14 |
15 | ArrayList namesList = new ArrayList<>(Arrays.asList("alex", "brian", "charles"));
16 |
17 | namesList.add(1, "Lokesh");
18 |
19 | System.out.println(namesList);
20 |
21 | //2
22 |
23 | ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c"));
24 |
25 | list.addAll(0, List.of("1", "2", "3"));
26 |
27 | System.out.println(list);
28 |
29 | //3
30 |
31 | Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
32 | namesList.add(10, "Lokesh");
33 | });
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/CheckEmptyList.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import com.google.common.collect.Iterables;
4 | import com.google.common.collect.Lists;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import org.apache.commons.collections4.CollectionUtils;
9 | import org.apache.commons.collections4.ListUtils;
10 | import org.junit.jupiter.api.Assertions;
11 |
12 | public class CheckEmptyList {
13 |
14 | public static void main(String[] args) {
15 | ArrayList list = new ArrayList();
16 |
17 | //1
18 |
19 | Assertions.assertTrue(list.isEmpty());
20 |
21 | list.add("1");
22 | Assertions.assertFalse(list.isEmpty());
23 |
24 | list.clear();
25 | Assertions.assertTrue(list.isEmpty());
26 |
27 | //2
28 | Assertions.assertTrue(list.size() == 0);
29 |
30 | list.add("1");
31 | Assertions.assertTrue(list.size() == 1);
32 |
33 | list.clear();
34 | Assertions.assertTrue(list.size() == 0);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/ClearArrayList.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import org.apache.commons.collections4.CollectionUtils;
6 | import org.junit.jupiter.api.Assertions;
7 |
8 | public class ClearArrayList {
9 |
10 | public static void main(String[] args) {
11 | ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
12 |
13 | list.clear();
14 |
15 | Assertions.assertEquals(0, list.size());
16 |
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials on [howtodoinjava.com](https://howtodoinjava.com/)
2 |
3 | * [Merge Two Lists](https://howtodoinjava.com/java/collections/arraylist/merge-arraylists/)
4 | * [Correct Way to Assert Two Equal Lists Ignoring Order](https://howtodoinjava.com/java/collections/arraylist/assert-two-equal-lists-ignoring-order/)
5 | *
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/RemoveDuplicates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.HashSet;
6 | import java.util.LinkedHashSet;
7 | import java.util.List;
8 | import java.util.Set;
9 | import java.util.stream.Collectors;
10 |
11 | public class RemoveDuplicates {
12 |
13 | public static void main(String[] args) {
14 | List items = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
15 |
16 | //1 - LinkedHashSet
17 | LinkedHashSet linkedHashSet = new LinkedHashSet<>(items);
18 | List listWithoutDuplicates = new ArrayList<>(linkedHashSet);
19 | System.out.println(listWithoutDuplicates);
20 |
21 | //2 - Streams
22 | listWithoutDuplicates = items.stream().distinct().collect(Collectors.toList());
23 | System.out.println(listWithoutDuplicates);
24 |
25 | //3 - Using HashSet
26 | Set set = new HashSet<>(items.size());
27 | items.removeIf(p -> !set.add(p));
28 | System.out.println(items);
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/RemoveIf.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.time.LocalDate;
4 | import java.time.Month;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.LinkedList;
8 | import java.util.function.Predicate;
9 |
10 | public class RemoveIf {
11 |
12 | public static void main(String[] args) {
13 | ArrayList numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
14 |
15 | numbers.removeIf(number -> number % 2 == 0);
16 |
17 | System.out.println(numbers);
18 |
19 | ArrayList employees = new ArrayList<>();
20 |
21 | employees.add(new Employee(1l, "Alex", ""));
22 | employees.add(new Employee(4l, "Brian", ""));
23 | employees.add(new Employee(3l, "Piyush", ""));
24 | employees.add(new Employee(5l, "Charles", ""));
25 | employees.add(new Employee(2l, "Pawan", ""));
26 |
27 | Predicate condition = employee -> employee.getFirstName().startsWith("P");
28 |
29 | employees.removeIf(condition);
30 |
31 | System.out.println(employees);
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/ReplaceItem.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.junit.jupiter.api.Assertions;
6 |
7 |
8 | public class ReplaceItem {
9 |
10 | public static void main(String[] args) {
11 | ArrayList list = new ArrayList<>(List.of("A", "B", "C", "D"));
12 |
13 | int index = list.indexOf("C");
14 | list.set(index, "C_NEW");
15 |
16 | Assertions.assertEquals("C_NEW", list.get(index));
17 |
18 |
19 | //2 - In single step replace D with D_NEW
20 | list.set( list.indexOf("D") , "D_NEW");
21 |
22 | Assertions.assertEquals("D_NEW", list.get(index));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/RetainsAll.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.stream.Stream;
6 |
7 | public class RetainsAll {
8 |
9 | public static void main(String[] args) {
10 | List list1 = new ArrayList<>(Stream.of(1, 2, 3, 4, 5).toList());
11 | List list2 = new ArrayList<>(Stream.of(1, 2, 3, 6, 7).toList());
12 |
13 | list1.retainAll(list2);
14 |
15 | System.out.println(list1); //[1, 2, 3]
16 | System.out.println(list2); //[1, 2, 3, 6, 7]
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/list/Task.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.list;
2 |
3 | public record Task(long id, String name, boolean status)
4 | implements Comparable {
5 |
6 | @Override
7 | public int compareTo(Task other) {
8 | return Long.compare(this.id, other.id);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/ConcurrentMapExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import java.util.Map;
4 | import java.util.Set;
5 | import java.util.concurrent.ConcurrentHashMap;
6 | import java.util.concurrent.ConcurrentMap;
7 | import java.util.stream.Stream;
8 |
9 | public class ConcurrentMapExample {
10 | public static void main(String[] args) {
11 | ConcurrentHashMap cmap = new ConcurrentHashMap<>();
12 | cmap.put(1, "Delhi");
13 | cmap.put(2, "NewYork");
14 | cmap.put(3, "London");
15 |
16 | // Iterating concurrent map keys
17 | for (Integer entry : cmap.keySet()) {
18 | System.out.println("Entry -- " + entry);
19 | }
20 |
21 | // Iterating concurrent map values
22 | for (String value : cmap.values()) {
23 | System.out.println("Value -- " + value);
24 | }
25 |
26 | // Iterating concurrent map entries
27 | for (Map.Entry entry : cmap.entrySet()) {
28 | System.out.println(entry.getKey() + " -- " + entry.getValue());
29 | }
30 |
31 | Stream.of(cmap.entrySet()).forEach(System.out::println);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/ConcurrentSkipListMapExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import java.util.Iterator;
4 | import java.util.concurrent.ConcurrentSkipListMap;
5 |
6 | public class ConcurrentSkipListMapExamples {
7 |
8 | public static void main(String[] args) {
9 | ConcurrentSkipListMap map = new ConcurrentSkipListMap<>();
10 | map.put(1, "A");
11 | map.put(2, "B");
12 | map.put(3, "C");
13 | map.put(4, "D");
14 | map.put(5, "E");
15 |
16 | System.out.println(map.headMap(3));
17 | System.out.println(map.tailMap(3));
18 |
19 | System.out.println(map.ceilingKey(3)); //4
20 | System.out.println(map.higherKey(3)); //4
21 | System.out.println(map.ceilingKey(4)); //4
22 | System.out.println(map.higherKey(4)); //5
23 | System.out.println(map.firstKey());
24 | System.out.println(map.lastKey());
25 |
26 |
27 |
28 |
29 |
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/EnumMapExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import java.util.EnumMap;
4 | import java.util.Map;
5 |
6 | import static com.howtodoinjava.core.collections.map.Direction.EAST;
7 |
8 | public class EnumMapExamples {
9 | public static void main(String[] args) {
10 | EnumMap allowedDirectionsMap = new EnumMap<>(Direction.class);
11 |
12 | allowedDirectionsMap.put(EAST, true);
13 | allowedDirectionsMap.put(null, true);
14 |
15 |
16 | EnumMap newMap = new EnumMap<>(allowedDirectionsMap);
17 |
18 | EnumMap newMapFromAnotherMap = new EnumMap<>(Map.of(EAST, true));
19 | }
20 | }
21 |
22 | enum Direction {
23 | EAST, WEST, NORTH, SOUTH
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials on [howtodoinjava.com](https://howtodoinjava.com/)
2 |
3 | * [Merge Two Maps](https://howtodoinjava.com/java/collections/hashmap/merge-two-hashmaps/)
4 | * [Java WeakHashMap](https://howtodoinjava.com/java/collections/java-weakhashmap/)
5 | * [Java IdentityHashMap](https://howtodoinjava.com/java/collections/java-identityhashmap/)
6 | * [Java Nested Map](https://howtodoinjava.com/java/collections/java-nested-map/)
7 | * [Java EnumMap](https://howtodoinjava.com/java/collections/java-enummap/)
8 | * [Java SubMap](https://howtodoinjava.com/java/collections/java-submap/)
9 | * [Inverting a Map In Java](https://howtodoinjava.com/java/collections/invert-java-map/)
10 | * [Convert List to Map](https://howtodoinjava.com/java/collections/convert-list-to-map/)
11 | * [Find Smallest and Largest Value in a Map](https://howtodoinjava.com/java/collections/hashmap/smallest-largest-value-in-map/)
12 | * [Java ConcurrentSkipListMap](https://howtodoinjava.com/java/collections/concurrentskiplistmap/)
13 | * [Java Map computeIfAbsent()](https://howtodoinjava.com/java/collections/hashmap/map-computeifabsent/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/SortAMapByKeysAndValues.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import java.util.Comparator;
4 | import java.util.HashMap;
5 | import java.util.LinkedHashMap;
6 | import java.util.Map;
7 | import java.util.TreeMap;
8 | import java.util.stream.Collectors;
9 |
10 | public class SortAMapByKeysAndValues {
11 |
12 | public static void main(String[] args) {
13 | Map unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);
14 |
15 | LinkedHashMap sortedMap = unsortedMap.entrySet()
16 | .stream()
17 | .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
18 | .collect(Collectors.toMap(
19 | Map.Entry::getKey,
20 | Map.Entry::getValue,
21 | (oldValue, newValue) -> oldValue, LinkedHashMap::new));
22 |
23 | System.out.println(sortedMap);
24 |
25 | Map sortedTreeMap = new TreeMap<>(Comparator.reverseOrder());
26 | sortedTreeMap.putAll(unsortedMap);
27 |
28 | System.out.println(sortedTreeMap);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/UnmodifiableMap.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import org.apache.commons.collections4.MapUtils;
4 |
5 | import java.util.Collections;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | public class UnmodifiableMap {
10 | public static void main(String[] args) {
11 | Map mutableMap = new HashMap<>();
12 | mutableMap.put("key1", "value1");
13 |
14 | Map unmodifiableMap
15 | = Collections.unmodifiableMap(mutableMap);
16 |
17 | //Throws java.lang.UnsupportedOperationException
18 | //unmodifiableMap.put("key2", "value2");
19 |
20 | //Changes are visible in both maps
21 | mutableMap.put("key2", "value2");
22 | System.out.println(unmodifiableMap); //{key1=value1, key2=value2}
23 |
24 | unmodifiableMap = MapUtils.unmodifiableMap(mutableMap);
25 | unmodifiableMap.put("key2", "value2");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/map/WeekHashMapExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.collections.map;
2 |
3 | import java.util.Map;
4 | import java.util.WeakHashMap;
5 |
6 | public class WeekHashMapExample {
7 | public static void main(String[] args) throws InterruptedException {
8 | Map map = new WeakHashMap<>();
9 |
10 | MapKey key1 = new MapKey("1");
11 | MapKey key2 = new MapKey("2");
12 |
13 | map.put(key1, "1");
14 | map.put(key2, "2");
15 |
16 | System.out.println(map);
17 |
18 | key1 = null;
19 |
20 | System.gc();
21 | Thread.sleep(10000);
22 |
23 | System.out.println(map);
24 | }
25 | }
26 |
27 | final class MapKey {
28 | String key;
29 | public MapKey(String key) {
30 | this.key = key;
31 | }
32 |
33 | public String getKey() {
34 | return key;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "MapKey{" +
40 | "key='" + key + '\'' +
41 | '}';
42 | }
43 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/collections/queue/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/java/com/howtodoinjava/core/collections/queue/README.md
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/Employee.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Collections;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 | import java.util.stream.Collectors;
9 | import java.util.stream.Stream;
10 |
11 | public class Employee {
12 |
13 | public static void main(String[] args) {
14 | Stream tokenStream = Stream.of("A", "B", "C", "D");
15 | ArrayList tokenList = tokenStream.collect(Collectors.toCollection(ArrayList::new));
16 | tokenList.add("e");
17 | System.out.println(tokenList);
18 |
19 | List list = Arrays.asList("A", "B", "C");
20 | list.add("e");
21 | System.out.println(list);
22 |
23 | ArrayList arraylist = new ArrayList<>(Arrays.asList("A", "B", "C"));
24 | }
25 |
26 | }
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/BinaryOctalAndHex.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal;
2 |
3 | public class BinaryOctalAndHex {
4 |
5 | public static void main(String[] args) {
6 |
7 | int number1 = 0X10D;
8 |
9 | System.out.println(number1);
10 |
11 | int number2 = 0B11010;
12 |
13 | System.out.println(number2);
14 |
15 | Integer number3 = 01560;
16 |
17 | System.out.println(number3);
18 |
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingBigIntegerClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | import java.math.BigInteger;
4 |
5 | public class ExampleUsingBigIntegerClass {
6 |
7 | public static void main(String[] args) {
8 |
9 | BigInteger decimal = new BigInteger("269");
10 |
11 | System.out.println(decimal.toString(16));
12 |
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingDouble.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class ExampleUsingDouble {
4 |
5 | public static void main(String[] args) {
6 |
7 | double number = 333.44d;
8 |
9 | String hex = Double.toHexString(number);
10 |
11 | System.out.println(hex);
12 |
13 | hex = String.format("%x", number);
14 |
15 | System.out.println(hex);
16 |
17 | hex = String.format("%x", number);
18 |
19 | System.out.println(hex);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingIntegerClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class ExampleUsingIntegerClass {
4 |
5 | private static String usingToString(int number) {
6 |
7 | return Integer.toString(number, 16);
8 |
9 | }
10 |
11 | private static String usingToHexString(int number) {
12 |
13 | return Integer.toHexString(number);
14 |
15 | }
16 |
17 | public static void main(String[] args) {
18 |
19 | int number = 269;
20 |
21 | System.out.println(usingToString(number));
22 |
23 | System.out.println(usingToHexString(number));
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingLongClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class ExampleUsingLongClass {
4 |
5 | private static String usingToString(long number) {
6 |
7 | return Long.toString(number, 16);
8 |
9 | }
10 |
11 | private static String usingToHexString(long number) {
12 |
13 | return Long.toHexString(number);
14 |
15 | }
16 |
17 | public static void main(String[] args) {
18 |
19 | long number = 269;
20 |
21 | System.out.println(usingToString(number));
22 |
23 | System.out.println(usingToHexString(number));
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingRawMethod.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class ExampleUsingRawMethod {
4 |
5 | public static String convertToHex(int number) {
6 |
7 | if (number <= 0) {
8 | return "0";
9 | }
10 |
11 | int remainder;
12 | StringBuilder result = new StringBuilder();
13 | String tokens = "0123456789ABCDEF";
14 |
15 | while (number > 0) {
16 | remainder = number % 16;
17 | result.insert(0, tokens.charAt(remainder));
18 | number = number / 16;
19 | }
20 | return result.toString();
21 | }
22 |
23 | public static void main(String[] args) {
24 |
25 | String hex = convertToHex(269);
26 | System.out.println(hex); // '10D'
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/ExampleUsingStringClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class ExampleUsingStringClass {
4 |
5 | private static String usingFormat(int number) {
6 |
7 | return String.format("%x", number);
8 |
9 | }
10 |
11 | private static String usingFormatMinimum4Digits(int number) {
12 |
13 | return String.format("%04x", number);
14 |
15 | }
16 |
17 | public static void main(String[] args) {
18 |
19 | int number = 269;
20 |
21 | System.out.println(usingFormat(number));
22 |
23 | System.out.println(usingFormatMinimum4Digits(number));
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/decimaltohex/FloatingPointDecimalToHex.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.decimaltohex;
2 |
3 | public class FloatingPointDecimalToHex {
4 |
5 | public static void main(String[] args) {
6 |
7 | double number = 333.44d;
8 |
9 | String hex = Double.toHexString(number);
10 |
11 | System.out.println(hex);
12 |
13 | float number1 = 333.44f;
14 |
15 | hex = Float.toHexString(number1);
16 |
17 | System.out.println(hex);
18 |
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/hextodecimal/ExampleUsingBigIntegerClass.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.hextodecimal;
2 |
3 | import java.math.BigInteger;
4 |
5 | public class ExampleUsingBigIntegerClass {
6 |
7 | public static void main(String[] args) {
8 |
9 | BigInteger decimal = new BigInteger("10d",16);
10 |
11 | System.out.println(decimal);
12 |
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/hextodecimal/ExampleUsingRawMethod.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.hextodecimal;
2 |
3 | public class ExampleUsingRawMethod {
4 |
5 | public static int convertHexToDecimal(String hex) {
6 |
7 | String tokens = "0123456789ABCDEF";
8 | hex = hex.toUpperCase();
9 | int result = 0;
10 |
11 | for (int i = 0; i < hex.length(); i++) {
12 |
13 | int n = tokens.indexOf(hex.charAt(i));
14 | result = result * 16 + n;
15 | }
16 | return result;
17 | }
18 |
19 | public static void main(String[] args) {
20 |
21 | System.out.println(convertHexToDecimal("10D"));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datatypes/decimalandhexadecimal/hextodecimal/FloatingPointHexToDecimal.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datatypes.decimalandhexadecimal.hextodecimal;
2 |
3 |
4 | public class FloatingPointHexToDecimal {
5 |
6 | public static void main(String[] args) {
7 |
8 | String myString = "BF800000";
9 | Long i = Long.parseLong(myString, 16);
10 | Float f = Float.intBitsToFloat(i.intValue());
11 |
12 | //converted float value
13 | System.out.println(f);
14 |
15 | //Convert the float back to hex and verify
16 | System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
17 |
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/CheckWeekendJava7.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.util.Calendar;
4 | import java.util.Date;
5 |
6 | public class CheckWeekendJava7 {
7 | public static void main(final String[] args) {
8 | Date today = new Date();
9 | System.out.println("Is weekend : " + isWeekend(today));
10 |
11 | @SuppressWarnings("deprecation")
12 | Date someDate = new Date(2021, 0, 2);
13 | System.out.println("Is weekend : " + isWeekend(someDate));
14 | }
15 |
16 | public static boolean isWeekend(final Date d) {
17 | Calendar cal = Calendar.getInstance();
18 | cal.setTime(d);
19 |
20 | int day = cal.get(Calendar.DAY_OF_WEEK);
21 | return day == Calendar.SATURDAY || day == Calendar.SUNDAY;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/CheckWeekendJava8.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.DayOfWeek;
4 | import java.time.LocalDate;
5 | import java.time.temporal.ChronoField;
6 |
7 | public class CheckWeekendJava8 {
8 | public static void main(final String[] args) {
9 | LocalDate today = LocalDate.now();
10 | System.out.println("Is weekend : " + isWeekend(today));
11 |
12 | LocalDate someDate = LocalDate.of(2021, 1, 2); // 2nd-Jan-2021
13 | System.out.println("Is weekend : " + isWeekend(someDate));
14 | }
15 |
16 | public static boolean isWeekend(final LocalDate ld) {
17 | DayOfWeek day = DayOfWeek.of(ld.get(ChronoField.DAY_OF_WEEK));
18 | return day == DayOfWeek.SUNDAY || day == DayOfWeek.SATURDAY;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/CurrentTimeStamp.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.sql.Timestamp;
4 | import java.time.Instant;
5 | import java.time.ZoneId;
6 | import java.time.format.DateTimeFormatter;
7 | import java.util.Date;
8 |
9 | public class CurrentTimeStamp {
10 | public static void main(final String[] args) {
11 | Instant instant = Instant.now();
12 | System.out.println(instant);
13 |
14 | DateTimeFormatter formatter = DateTimeFormatter
15 | .ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
16 | .withZone(ZoneId.of("GMT"));
17 |
18 | String formattedString = formatter.format(instant); // 15-02-2022 12:43
19 | System.out.println(formattedString);
20 |
21 | // Java 7
22 |
23 | Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
24 |
25 | Date date = new Date();
26 | Timestamp timestamp2 = new Timestamp(date.getTime());
27 |
28 | System.out.println(timestamp1); //2022-02-15 13:55:56.18
29 | System.out.println(timestamp2); //2022-02-15 13:55:56.18
30 |
31 | formattedString = formatter.format(timestamp1.toInstant());
32 | System.out.println(formattedString);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/DateConversionUtils.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.Instant;
4 | import java.time.LocalDate;
5 | import java.time.LocalDateTime;
6 | import java.time.ZoneId;
7 | import java.util.Date;
8 |
9 | public class DateConversionUtils {
10 |
11 | private DateConversionUtils() {
12 | }
13 |
14 | public static Date asDate(LocalDate localDate) {
15 | return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
16 | }
17 |
18 | public static Date asDate(LocalDateTime localDateTime) {
19 | return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
20 | }
21 |
22 | public static LocalDate asLocalDate(Date date) {
23 | return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
24 | }
25 |
26 | public static LocalDateTime asLocalDateTime(Date date) {
27 | return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/DateTimeFormatterWithTimeZone.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.ZoneId;
4 | import java.time.ZonedDateTime;
5 | import java.time.format.DateTimeFormatter;
6 |
7 | public class DateTimeFormatterWithTimeZone {
8 | private static final String DT_PATTERN = "dd/MM/yyyy HH:mm z";
9 |
10 | public static void main(String[] args) {
11 | DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern(DT_PATTERN);
12 |
13 | ZonedDateTime zdt = ZonedDateTime.now();
14 |
15 | //Formatting
16 |
17 | String localizedDateTime = dtFormatter.format(zdt);
18 | System.out.println(localizedDateTime);
19 |
20 | String localizedDateTimeInUTC = dtFormatter.format(zdt.withZoneSameInstant(ZoneId.of("UTC-4")));
21 | System.out.println(localizedDateTimeInUTC);
22 |
23 | //Parsing
24 |
25 | ZonedDateTime localizedDateTimeParsed = ZonedDateTime.parse(localizedDateTime, dtFormatter);
26 | System.out.println(localizedDateTimeParsed);
27 | System.out.println(localizedDateTimeParsed.getOffset().getTotalSeconds());
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/DayOfWeekExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.DayOfWeek;
4 | import java.time.LocalDate;
5 | import java.time.format.TextStyle;
6 | import java.util.Locale;
7 |
8 | public class DayOfWeekExample {
9 | public static void main(String[] args)
10 | {
11 | LocalDate today = LocalDate.now();
12 |
13 | System.out.println( today.getDayOfWeek() );
14 | System.out.println( today.getDayOfWeek().getValue() );
15 |
16 | String textValue = getDayString(today, Locale.getDefault());
17 |
18 | System.out.println(textValue);
19 |
20 | textValue = getDayString(today, Locale.GERMAN);
21 |
22 | System.out.println(textValue);
23 | }
24 |
25 | public static String getDayString(LocalDate date, Locale locale) {
26 | DayOfWeek day = date.getDayOfWeek();
27 | return day.getDisplayName(TextStyle.FULL, locale);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/DaysBetweenDates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.temporal.ChronoUnit;
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 | import java.util.stream.Stream;
8 |
9 | public class DaysBetweenDates {
10 | public static void main(final String[] args) {
11 | LocalDate date1 = LocalDate.now();
12 | LocalDate date2 = date1.plusDays(99);
13 |
14 | long diffInDays = ChronoUnit.DAYS.between(date1, date2);
15 |
16 | System.out.println(diffInDays);
17 |
18 | diffInDays = date1.until(date2, ChronoUnit.DAYS);
19 |
20 | System.out.println(diffInDays);
21 |
22 | LocalDate startDate = LocalDate.now();
23 | LocalDate endDate = startDate.plusMonths(2);
24 |
25 | long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
26 |
27 | List listOfDates = Stream.iterate(startDate, date -> date.plusDays(1))
28 | .limit(numOfDays)
29 | .collect(Collectors.toList());
30 |
31 | System.out.println(listOfDates);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/ExtractDayMonthYear.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.util.Calendar;
5 | import java.util.Date;
6 |
7 | public class ExtractDayMonthYear {
8 | public static void main(final String[] args) {
9 | LocalDate today = LocalDate.now();
10 |
11 | int day = today.getDayOfMonth();
12 | int month = today.getMonthValue();
13 | int year = today.getYear();
14 |
15 | System.out.println(day);
16 | System.out.println(month);
17 | System.out.println(year);
18 |
19 | //Java 7
20 |
21 | Date date = new Date();
22 | Calendar calendar = Calendar.getInstance();
23 | calendar.setTime(date);
24 |
25 | day = calendar.get(Calendar.DAY_OF_MONTH);
26 | month = calendar.get(Calendar.MONTH);
27 | year = calendar.get(Calendar.YEAR);
28 |
29 | System.out.println(day);
30 | System.out.println(month);
31 | System.out.println(year);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/FirstLastDayOfYear.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.temporal.TemporalAdjusters;
5 |
6 | public class FirstLastDayOfYear {
7 |
8 | public static void main(String[] args) {
9 | int year = 2024;
10 |
11 | LocalDate firstDay = LocalDate.of(year, 1, 1);
12 | System.out.println(firstDay);
13 |
14 | LocalDate lastDay = LocalDate.of(year, 12, 31);
15 | System.out.println(lastDay);
16 |
17 | System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()));
18 | System.out.println(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/FormatLocalDate.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.format.DateTimeFormatter;
5 | import java.time.format.FormatStyle;
6 |
7 | public class FormatLocalDate {
8 | public static void main(String[] args) {
9 | LocalDate today = LocalDate.now();
10 |
11 | String formattedDate = today.format(DateTimeFormatter
12 | .ofLocalizedDate(FormatStyle.LONG));
13 | System.out.println("LONG format: " + formattedDate);
14 |
15 | formattedDate = today.format(DateTimeFormatter
16 | .ofLocalizedDate(FormatStyle.MEDIUM));
17 | System.out.println("MEDIUM format: " + formattedDate);
18 |
19 | formattedDate = today.format(DateTimeFormatter
20 | .ofLocalizedDate(FormatStyle.SHORT));
21 | System.out.println("SHORT format: " + formattedDate);
22 |
23 | formattedDate = today.format(DateTimeFormatter
24 | .ofLocalizedDate(FormatStyle.FULL));
25 | System.out.println("FULL format: " + formattedDate);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/FormatLocalDateTime.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDateTime;
4 | import java.time.format.DateTimeFormatter;
5 |
6 | public class FormatLocalDateTime {
7 |
8 | final static DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
9 | final static DateTimeFormatter CUSTOM_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
10 |
11 | public static void main(String[] args) {
12 | LocalDateTime currentDateTime = LocalDateTime.now();
13 | System.out.println(currentDateTime);
14 |
15 | String formattedDateTime = currentDateTime.format(ISO_FORMATTER);
16 | System.out.println(formattedDateTime);
17 |
18 |
19 | String formattedString = currentDateTime.format(CUSTOM_FORMATTER);
20 | System.out.println(formattedString);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/FormatMilliseconds.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.Duration;
4 |
5 | import org.apache.commons.lang3.time.DurationFormatUtils;
6 |
7 | public class FormatMilliseconds {
8 | public static void main(final String[] args) {
9 |
10 | long millis = 54321000;
11 |
12 | //Java 8
13 | Duration duration = Duration.ofMillis(millis);
14 |
15 | long h = duration.toHours();
16 | long m = duration.toMinutes() % 60;
17 | long s = duration.getSeconds() % 60;
18 |
19 | String timeInHms = String.format("%02d:%02d:%02d", h, m, s);
20 | System.out.println(timeInHms);
21 |
22 | //Apache Commons
23 | timeInHms = DurationFormatUtils.formatDuration(millis, "HH:mm:ss", true);
24 | System.out.println(timeInHms);
25 | }
26 | }
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/FormatZonedDateTime.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.ZonedDateTime;
4 | import java.time.format.DateTimeFormatter;
5 |
6 | public class FormatZonedDateTime {
7 | public static void main(String[] args) {
8 | ZonedDateTime zdt = ZonedDateTime.now();
9 |
10 | String formattedZdt = zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
11 | System.out.println(formattedZdt);
12 |
13 | formattedZdt = zdt.format(DateTimeFormatter.ISO_DATE_TIME);
14 | System.out.println(formattedZdt);
15 |
16 | formattedZdt = zdt.format(DateTimeFormatter.ISO_INSTANT);
17 | System.out.println(formattedZdt);
18 |
19 | //Custom format
20 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
21 | formattedZdt = zdt.format(formatter);
22 | System.out.println(formattedZdt);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/InstantToZonedDateTime.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.Instant;
4 | import java.time.ZoneId;
5 | import java.time.ZoneOffset;
6 | import java.time.ZonedDateTime;
7 |
8 | public class InstantToZonedDateTime {
9 |
10 | public static void main(String[] args) {
11 | Instant instant = Instant.now();
12 | System.out.println(instant);
13 |
14 | ZonedDateTime istDateTime = instant.atZone(ZoneId.of("Asia/Kolkata"));
15 | System.out.println(istDateTime);
16 |
17 | ZonedDateTime istDateTime1 = ZonedDateTime.ofInstant(instant, ZoneOffset.of("+05:30"));
18 | System.out.println(istDateTime1);
19 |
20 | Instant instant1 = ZonedDateTime.now().toInstant();
21 | System.out.println(instant1);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/NewDateTimeAPI.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.OffsetDateTime;
4 | import java.time.ZonedDateTime;
5 | import java.util.Optional;
6 | import java.util.stream.Stream;
7 | import org.junit.jupiter.api.Assertions;
8 |
9 | public class NewDateTimeAPI {
10 |
11 | public static void main(String[] args) {
12 | OffsetDateTime offsetDate = OffsetDateTime.now();
13 | System.out.println(offsetDate);
14 |
15 | ZonedDateTime zonedDateTime = ZonedDateTime.now();
16 | System.out.println(zonedDateTime);
17 |
18 | Optional optional = Stream.empty().findAny();
19 | Assertions.assertTrue(optional.isEmpty());
20 |
21 | optional = Stream.of("one", "two", "three", "four")
22 | .findAny();
23 |
24 | Assertions.assertTrue(optional.isPresent());
25 | Assertions.assertEquals("one", optional.get());
26 |
27 |
28 | optional = Stream.of("one", "two", "three", "four")
29 | .parallel()
30 | .findAny();
31 |
32 | Assertions.assertTrue(optional.isPresent());
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/SetJvmTimezone.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.util.TimeZone;
4 |
5 | public class SetJvmTimezone {
6 | public static void main(String[] args) {
7 |
8 | /*//Setting UTC time zone - 1
9 | System.setProperty("user.timezone", "UTC");
10 |
11 |
12 | //Setting UTC time zone - 2
13 | TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
14 | TimeZone.setDefault(utcTimeZone);*/
15 |
16 | //Verify
17 | TimeZone timeZone = TimeZone.getDefault();
18 | System.out.printf("DisplayName = %s, ID = %s, offset = %s",
19 | timeZone.getDisplayName(),timeZone.getID(),timeZone.getRawOffset());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/TemporalQueriesExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.LocalTime;
5 | import java.time.temporal.TemporalQuery;
6 |
7 | public class TemporalQueriesExample
8 | {
9 | public static void main(String[] args)
10 | {
11 | LocalTime now = LocalTime.now();
12 | LocalDate today = LocalDate.now();
13 |
14 | System.out.println("Currently Working :: " + now.query(WorkingHoursQuery));
15 | System.out.println("Current Financial Quarter :: " + today.query(CurrentQuarterQuery));
16 | }
17 |
18 | private static final TemporalQuery WorkingHoursQuery = temporal -> {
19 | LocalTime t = LocalTime.from(temporal);
20 | return t.compareTo(LocalTime.of(9, 0)) >= 0
21 | && t.compareTo(LocalTime.of(17, 0)) < 0;
22 | };
23 |
24 | private static final TemporalQuery CurrentQuarterQuery = temporal -> {
25 | LocalDate date = LocalDate.from(temporal);
26 | return (date.getMonthValue() / 3) + 1;
27 | };
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/ValidateMultipleDateFormats.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | public class ValidateMultipleDateFormats {
4 | public static void main(String[] args) {
5 | //TODO
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/datetime/WeeksBetweenDates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.temporal.ChronoUnit;
5 |
6 | public class WeeksBetweenDates {
7 |
8 | public static void main(String[] args) {
9 | LocalDate startLd = LocalDate.of(2023, 8, 5);
10 | LocalDate endLd = LocalDate.of(2023, 9, 5);
11 | long numWeeks = ChronoUnit.WEEKS.between(startLd, endLd);
12 | System.out.println(numWeeks);
13 |
14 | long daysDifference = ChronoUnit.DAYS.between(startLd, endLd); // 31
15 | int extraDays = Long.valueOf(daysDifference % 7).intValue(); //3
16 | System.out.println(extraDays);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/enums/EnumWithStringsExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.enums;
2 |
3 | import java.util.Arrays;
4 | import java.util.Optional;
5 |
6 | public class EnumWithStringsExample
7 | {
8 | public static void main(String[] args)
9 | {
10 | String url = "https://sit.domain.com:2019/";
11 |
12 | Optional env = Environment.get(url);
13 |
14 | System.out.println(env.get());
15 | }
16 | }
17 |
18 | enum Environment
19 | {
20 | PROD("https://prod.domain.com:1088/"),
21 | SIT("https://sit.domain.com:2019/"),
22 | CIT("https://cit.domain.com:8080/"),
23 | DEV("https://dev.domain.com:21323/");
24 |
25 | private String url;
26 |
27 | Environment(String envUrl) {
28 | this.url = envUrl;
29 | }
30 |
31 | public String getUrl() {
32 | return url;
33 | }
34 |
35 | //****** Reverse Lookup ************//
36 |
37 | public static Optional get(String url) {
38 | return Arrays.stream(Environment.values())
39 | .filter(env -> env.url.equals(url))
40 | .findFirst();
41 | }
42 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/enums/PathUtils.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.enums;
2 |
3 | import java.nio.file.Path;
4 | import java.nio.file.Paths;
5 |
6 | public enum PathUtils {
7 | INSTANCE;
8 |
9 | public static PathUtils getInstance() {
10 | return INSTANCE;
11 | }
12 |
13 | PathUtils() {
14 | rootPath = Paths.get("");
15 | }
16 |
17 | private final Path rootPath;
18 |
19 | public Path getRootPath() {
20 | return rootPath;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/examples/AddTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.examples;
2 |
3 | import java.util.Scanner;
4 |
5 | public class AddTwoIntegers
6 | {
7 | public static void main(String[] args)
8 | {
9 | int firstInteger = 0;
10 | int secondInteger = 0;
11 |
12 | Scanner sc = new Scanner(System.in);
13 | System.out.println("Enter First Number: ");
14 | firstInteger = sc.nextInt();
15 |
16 | System.out.println("Enter Second Number: ");
17 | secondInteger = sc.nextInt();
18 |
19 | sc.close();
20 |
21 | int sum = firstInteger + secondInteger;
22 |
23 | System.out.println("The sum of both integers: " + sum);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/examples/AgeCalculator.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.examples;
2 |
3 | import java.time.LocalDate;
4 | import java.time.Month;
5 | import java.time.Period;
6 |
7 | public class AgeCalculator {
8 | public static void main(final String[] args) {
9 | LocalDate today = LocalDate.now(); // Today's date
10 | LocalDate birthday = LocalDate.of(1980, Month.JANUARY, 1); // Birth date
11 |
12 | Period p = Period.between(birthday, today);
13 |
14 | // Now access the values as below
15 | System.out.println(p.getDays());
16 | System.out.println(p.getMonths());
17 | System.out.println(p.getYears());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/examples/ConsoleExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.examples;
2 |
3 | import java.io.Console;
4 | import java.io.Reader;
5 | import java.util.Scanner;
6 |
7 | public class ConsoleExamples
8 | {
9 | public static void main(String[] args)
10 | {
11 | Console console = System.console();
12 |
13 | if(console == null) {
14 | System.out.println("Console is not available to current JVM process");
15 | return;
16 | }
17 |
18 | //1
19 | String userName = console.readLine("Enter the username: ");
20 | System.out.println("Entered username: " + userName);
21 |
22 | //2
23 | char[] password = console.readPassword("Enter the password: ");
24 | System.out.println("Entered password: " + new String(password));
25 |
26 | //3
27 | Reader consoleReader = console.reader();
28 | Scanner scanner = new Scanner(consoleReader);
29 |
30 | System.out.println("Enter age:");
31 | int age = scanner.nextInt();
32 | System.out.println("Entered age: " + age);
33 |
34 | scanner.close();
35 |
36 | //write to console
37 | console.printf("My name is %s and my age is %d", userName, age);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/examples/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | 1. [Java - Program to calculate average of N numbers](https://howtodoinjava.com/java-programs/calculate-average-of-n-numbers/)
4 | 2. [Java - Console Input and Output Examples](https://howtodoinjava.com/java-programs/console-input-output/)
5 | 3. [Java - Program to Add Two Integers](https://howtodoinjava.com/java-programs/program-to-add-two-integers/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/exceptions/StackTrace.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.exceptions;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.io.StringWriter;
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import java.util.stream.Collectors;
9 | import org.apache.commons.lang3.exception.ExceptionUtils;
10 |
11 | public class StackTrace {
12 |
13 | public static void main(String[] args) {
14 | NullPointerException npe = new NullPointerException("Custom error");
15 |
16 | //1. Core Java
17 | String errorStr = null;
18 |
19 | try (StringWriter sw = new StringWriter();
20 | PrintWriter pw = new PrintWriter(sw)) {
21 | npe.printStackTrace(pw);
22 | errorStr = sw.toString();
23 |
24 | } catch (IOException e) {
25 | throw new RuntimeException("Error while converting the stacktrace");
26 | }
27 |
28 | System.out.println(errorStr);
29 |
30 | //2. ExceptionUtils
31 |
32 | errorStr = ExceptionUtils.getStackTrace(npe);
33 | System.out.println(errorStr);
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/objectToMap/Employee.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.objectToMap;
2 |
3 | import java.time.LocalDate;
4 | import java.util.List;
5 | import lombok.AllArgsConstructor;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 |
9 | @Data
10 | @AllArgsConstructor
11 | @NoArgsConstructor
12 | public class Employee {
13 | private Integer id;
14 | private String name;
15 | private LocalDate dateOfBirth;
16 | private List locations;
17 | private List roles;
18 | }
19 |
20 | @Data
21 | @AllArgsConstructor
22 | @NoArgsConstructor
23 | class Role {
24 | private Integer id;
25 | private String name;
26 | }
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/objectToMap/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | . [Convert an Object to Map](https://howtodoinjava.com/java/basics/convert-object-to-map/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/optional/OptionalExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.optional;
2 |
3 | import java.util.Optional;
4 |
5 | public class OptionalExamples {
6 |
7 | public static void main(String[] args) {
8 | Optional optionalValue = Optional.of("Hello");
9 | String result = optionalValue.orElse( generateDefaultValue() ); // Using orElse()
10 | System.out.println(STR."Result using orElse(): \{result}");
11 |
12 | result = optionalValue.orElseGet(() -> generateDefaultValue() ); // Using orElseGet()
13 | System.out.println(STR."Result using orElseGet(): \{result}");
14 | }
15 |
16 | public static String generateDefaultValue() {
17 | System.out.println("Generating Default Value");
18 | return "Default Value";
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/predicate/IntPredicateExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.predicate;
2 |
3 | import java.util.List;
4 | import java.util.function.IntPredicate;
5 | import java.util.stream.Collectors;
6 | import java.util.stream.IntStream;
7 |
8 | public class IntPredicateExample
9 | {
10 | public static void main(String[] args)
11 | {
12 | IntPredicate isOdd = argument -> argument % 2 == 1;
13 |
14 | IntStream stream = IntStream.range(1, 20);
15 |
16 | List oddNumbers = stream.filter(isOdd.and(IntPredicateExample::isPrime))
17 | .boxed()
18 | .collect(Collectors.toList());
19 |
20 | System.out.println(oddNumbers);
21 | }
22 |
23 | public static boolean isPrime(int i)
24 | {
25 | IntPredicate isDivisible = index -> i % index == 0;
26 | return i > 1 && IntStream.range(2, i).noneMatch(isDivisible);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/random/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | * [Generate Random Numbers in a Range](https://howtodoinjava.com/java/generate-random-numbers-in-range/)
4 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/random/RandomNumberStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.random;
2 |
3 | import java.util.Random;
4 | import java.util.stream.IntStream;
5 |
6 | public class RandomNumberStream
7 | {
8 | public static void main(String[] args)
9 | {
10 | IntStream randomNumberStream = new Random().ints(10, 10000);
11 |
12 | randomNumberStream
13 | .limit(6)
14 | .forEach(System.out::println);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/random/SimpleRandoms.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.random;
2 |
3 | import java.util.Random;
4 | import java.util.SplittableRandom;
5 | import java.util.UUID;
6 |
7 | public class SimpleRandoms {
8 | public static void main(String[] args) {
9 | Random randomGenerator = new Random();
10 |
11 | // Upper bound 10000
12 | System.out.println(randomGenerator.nextInt(10_000));
13 | System.out.println(randomGenerator.nextInt(10_000));
14 |
15 | // No upper bound
16 | System.out.println(randomGenerator.nextInt());
17 | System.out.println(randomGenerator.nextInt());
18 |
19 | String uuid = UUID.randomUUID().toString();
20 | System.out.println(uuid);
21 |
22 | SplittableRandom random = new SplittableRandom();
23 | SplittableRandom splitted = random.split();
24 |
25 | System.out.println(random.nextInt(10000));
26 | System.out.println(splitted.nextInt(10000));
27 | System.out.println(random.nextInt(10000));
28 | System.out.println(splitted.nextInt(10000));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/recursion/RecursionDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.recursion;
2 |
3 | public class RecursionDemo {
4 | public static void main(String[] args) {
5 | var result = sum(1L, 40000L).run();
6 | System.out.println(result);
7 |
8 | //var result = simpleRecursiveSum(1L, 40000L);
9 | //System.out.println(result); //Exception in thread "main" java.lang.StackOverflowError
10 | }
11 |
12 | static long simpleRecursiveSum(long total, long summand) {
13 | if (summand == 1L) {
14 | return total;
15 | }
16 | return simpleRecursiveSum(total + summand, summand - 1L);
17 | }
18 |
19 | static RecursiveCall sum(Long total, Long summand) {
20 | if (summand == 1) {
21 | return RecursiveCall.done(total);
22 | }
23 | return () -> sum(total + summand, summand - 1L);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/recursion/RecursiveCall.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.recursion;
2 |
3 | import java.util.stream.Stream;
4 |
5 | @FunctionalInterface
6 | public interface RecursiveCall {
7 | RecursiveCall apply();
8 |
9 | default boolean isComplete() {
10 | return false;
11 | }
12 |
13 | default T result() {
14 | throw new Error("not implemented");
15 | }
16 |
17 | default T run() {
18 | return Stream.iterate(this, RecursiveCall::apply)
19 | .filter(RecursiveCall::isComplete).findFirst().get().result();
20 | }
21 |
22 | static RecursiveCall done(T value) {
23 |
24 | return new RecursiveCall() {
25 |
26 | @Override
27 | public boolean isComplete() {
28 | return true;
29 | }
30 |
31 | @Override
32 | public T result() {
33 | return value;
34 | }
35 |
36 | @Override
37 | public RecursiveCall apply() {
38 | throw new UnsupportedOperationException();
39 | }
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/security/AES256Example.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.security;
2 |
3 | public class AES256Example {
4 |
5 | public static void main(String[] args) {
6 | // Define your secret key and salt (keep these secure and don't hardcode in production)
7 | String secretKey = "MySecretKey";
8 | String salt = "MySalt";
9 |
10 | // String to be encrypted
11 | String originalString = "Hello, this is a secret message.";
12 |
13 | // Encrypt the string
14 | String encryptedString = AES256.encrypt(originalString, secretKey, salt);
15 | if (encryptedString != null) {
16 | System.out.println("Encrypted: " + encryptedString);
17 | } else {
18 | System.err.println("Encryption failed.");
19 | return;
20 | }
21 |
22 | // Decrypt the string
23 | String decryptedString = AES256.decrypt(encryptedString, secretKey, salt);
24 | if (decryptedString != null) {
25 | System.out.println("Decrypted: " + decryptedString);
26 | } else {
27 | System.err.println("Decryption failed.");
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/security/Base64Example.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.security;
2 |
3 | import java.util.Base64;
4 |
5 | public class Base64Example {
6 |
7 | public static void main(String[] args) {
8 | String originalInput = "hello world";
9 | String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
10 | System.out.println(encodedString);
11 |
12 | byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
13 | String decodedString = new String(decodedBytes);
14 | System.out.println(decodedString);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/security/Base64FileEncodeExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.security;
2 |
3 | import jakarta.xml.bind.DatatypeConverter;
4 | import java.io.File;
5 | import java.io.IOException;
6 | import java.nio.file.Files;
7 | import java.util.Base64;
8 |
9 | public class Base64FileEncodeExample {
10 |
11 | public static void main(String[] args) throws IOException {
12 | //TextFile
13 | File file = new File("c:/temp/output.txt");
14 | String encoded = Base64.getEncoder()
15 | .encodeToString(Files.readAllBytes(file.toPath()));
16 | System.out.println(encoded);
17 |
18 | byte[] decoded = Base64.getDecoder().decode(encoded);
19 | System.out.println(new String(decoded));
20 |
21 | //ImageFile
22 | File inImage = new File("c:/temp/avni.jpg");
23 | File outImage = new File("c:/temp/avni_new.jpg");
24 | byte[] encodedImageBytes = Base64.getEncoder().encode(Files.readAllBytes(inImage.toPath()));
25 | byte[] decodedImageBytes = Base64.getDecoder().decode(encodedImageBytes);
26 | Files.write(outImage.toPath(), decodedImageBytes);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/security/EdwardAlgoExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.security;
2 |
3 | import java.nio.charset.StandardCharsets;
4 | import java.security.*;
5 | import java.util.Base64;
6 |
7 | public class EdwardAlgoExample {
8 | public static void main(String[] args)
9 | throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
10 |
11 | KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed448");
12 | KeyPair kp = kpg.generateKeyPair();
13 |
14 | byte[] msg = "test_string".getBytes(StandardCharsets.UTF_8);
15 |
16 | Signature sig = Signature.getInstance("Ed448");
17 | sig.initSign(kp.getPrivate());
18 | sig.update(msg);
19 | byte[] s = sig.sign();
20 |
21 | String encodedString = Base64.getEncoder().encodeToString(s);
22 | System.out.println(encodedString);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/serialization/DeepCopyDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.serialization;
2 |
3 | import java.util.List;
4 |
5 | public class DeepCopyDemo {
6 |
7 | public static void main(String[] args) throws Exception {
8 |
9 | TestClass myClass = new TestClass("Lokesh", "Gupta", List.of("ADMIN", "USER"));
10 |
11 | System.out.println(myClass);
12 |
13 | TestClass deepCopiedInstance = myClass.deepCopy();
14 |
15 | System.out.println(deepCopiedInstance);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/sorting/ComparableExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | public class ComparableExamples {
9 | public static void main(String[] args) {
10 |
11 | List list = getUnsortedUsers();
12 |
13 | Collections.sort(list);
14 |
15 | System.out.println(list);
16 |
17 | List sortedList = list.stream()
18 | .sorted()
19 | .collect(Collectors.toList());
20 |
21 | System.out.println(sortedList);
22 | }
23 |
24 | private static List getUnsortedUsers() {
25 | return Arrays.asList(new User(1L, "A", "Q", Integer.valueOf(24)),
26 | new User(4L, "B", "P", Integer.valueOf(22)),
27 | new User(2L, "C", "O", Integer.valueOf(27)),
28 | new User(3L, "D", "N", Integer.valueOf(29)),
29 | new User(5L, "E", "M", Integer.valueOf(25)));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/sorting/FirstNameSorter.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.sorting;
2 |
3 | import java.util.Comparator;
4 |
5 | public class FirstNameSorter implements Comparator {
6 |
7 | @Override
8 | public int compare(User o1, User o2) {
9 | return o1.firstName().compareTo(o2.firstName());
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/sorting/User.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.sorting;
2 |
3 | import java.io.Serializable;
4 | import java.util.Objects;
5 |
6 | public record User(Long id, String firstName, String lastName, Integer age)
7 | implements Serializable, Comparable {
8 |
9 | public User {
10 | if (age < 18) {
11 | throw new IllegalArgumentException("You cannot hire a minor person");
12 | }
13 | }
14 |
15 | @Override
16 | public int compareTo(User o) {
17 | return this.id.intValue() - o.id.intValue();
18 | }
19 |
20 | @Override
21 | public int hashCode() {
22 | return Objects.hash(id);
23 | }
24 |
25 | @Override
26 | public boolean equals(Object obj) {
27 | if (this == obj)
28 | return true;
29 | if (obj == null)
30 | return false;
31 | if (getClass() != obj.getClass())
32 | return false;
33 | User other = (User) obj;
34 | return Objects.equals(id, other.id);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/AddRemoveItems.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | public class AddRemoveItems {
4 | public static void main(String[] args) {
5 |
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/BoxedStreamExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.util.List;
4 | import java.util.stream.Collectors;
5 | import java.util.stream.DoubleStream;
6 | import java.util.stream.IntStream;
7 | import java.util.stream.LongStream;
8 | import java.util.stream.Stream;
9 |
10 | public class BoxedStreamExample {
11 | @SuppressWarnings("unused")
12 | public static void main(final String[] args) {
13 | Stream stream = IntStream.of(1, 2, 3, 4, 5).boxed();
14 | Stream stream1 = LongStream.of(1, 2, 3, 4, 5).boxed();
15 | Stream stream2 = DoubleStream.of(1.0, 2.0, 3.0, 4.0, 5.0).boxed();
16 |
17 | //Compilation issue
18 | /*List list = IntStream.of(1,2,3,4,5)
19 | .collect(Collectors.toList());*/
20 |
21 | List list = IntStream.of(1,2,3,4,5)
22 | .boxed()
23 | .collect(Collectors.toList());
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/ChainedPredicate.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.function.Predicate;
6 | import java.util.stream.Collectors;
7 |
8 | public class ChainedPredicate {
9 | @SuppressWarnings("unused")
10 | public static void main(final String[] args) {
11 | List list = Arrays.asList("Aa", "Bb", "Cc", "Dd", "Ab", "Bc");
12 |
13 | Predicate startsWithA = s -> s.startsWith("A");
14 | Predicate startsWithB = s -> s.startsWith("B");
15 | Predicate containsC = s -> s.contains("c");
16 | Predicate notContainsC = s -> !s.contains("c");
17 |
18 | Predicate complexPredicate = startsWithA.or(startsWithB)
19 | .and(containsC.negate());
20 |
21 | List items = list.stream()
22 | .filter(complexPredicate)
23 | .collect(Collectors.toList());
24 |
25 | System.out.println(items);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/Main.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.util.stream.Collectors;
4 | import java.util.stream.Stream;
5 |
6 | public class Main
7 | {
8 | public static void main(final String[] args)
9 | {
10 | String message = "There are %d elements in the stream %n";
11 |
12 | long count = Stream.of("how", "to", "do", "in", "java").collect(Collectors.counting());
13 | System.out.printf(message, count);
14 |
15 | count = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).collect(Collectors.counting());
16 | System.out.printf(message, count);
17 |
18 | count = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).filter(i -> i % 2 == 0).collect(Collectors.counting());
19 | System.out.printf(message, count);
20 | }
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/Person.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.util.Objects;
4 |
5 | public record Person(Integer id, String fname, String lname)
6 | implements Comparable {
7 |
8 | @Override
9 | public boolean equals(final Object obj) {
10 | if (this == obj) {
11 | return true;
12 | }
13 | if (obj == null) {
14 | return false;
15 | }
16 | if (getClass() != obj.getClass()) {
17 | return false;
18 | }
19 | Person other = (Person) obj;
20 | return Objects.equals(id, other.id);
21 | }
22 |
23 | @Override
24 | public int compareTo(final Person p) {
25 | return this.id()
26 | .compareTo(p.id());
27 | }
28 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/README.md:
--------------------------------------------------------------------------------
1 | # Related Tutorials
2 |
3 | 1. [Filter a Map by List of Keys](https://howtodoinjava.com/java/stream/filter-map-by-list-of-keys/)
4 | 2. [Remove/Update Elements From List using Stream](https://howtodoinjava.com/java/stream/remove-update-stream-elements/)
5 | 3. [Java Predicate](https://howtodoinjava.com/java8/how-to-use-predicate-in-java-8/)
6 | 4. [Handle Exceptions Thrown in Java Streams](https://howtodoinjava.com/java/stream/handle-exceptions-in-stream/)
7 | 5. [Sort a Map by Keys](https://howtodoinjava.com/java/sort/java-sort-map-by-key/)
8 | 6. [Sort a Map by Values](https://howtodoinjava.com/java/sort/java-sort-map-by-values/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/RemoveOrUpdateElements.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.time.LocalDate;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | public class RemoveOrUpdateElements {
8 |
9 | public static void main(String[] args) {
10 |
11 | List list = List.of(
12 | new Employee(1, "Alex", LocalDate.of(1990, 1, 2), 100d),
13 | new Employee(2, "Alok", LocalDate.of(1992, 1, 2), 200d),
14 | new Employee(3, "Brian", LocalDate.of(1994, 1, 2), 300d),
15 | new Employee(4, "Charles", LocalDate.of(1996, 1, 2), 400d));
16 |
17 | List modifiedList = list.stream()
18 | .filter(e -> e.getName().startsWith("A"))
19 | .collect(Collectors.toList());
20 |
21 | //Employees whose names start with "A"
22 | System.out.println(modifiedList);
23 |
24 | List newList = list.stream()
25 | .map(e -> {
26 | e.setSalary(e.getSalary() + 100);
27 | return e;
28 | })
29 | .collect(Collectors.toList());
30 |
31 | //Employees salary incremented by 100
32 | System.out.println(newList);
33 | }
34 | }
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/StreamOfDates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.time.LocalDate;
4 | import java.time.Period;
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 | import java.util.stream.Stream;
8 |
9 | public class StreamOfDates {
10 | @SuppressWarnings("unused")
11 | public static void main(final String[] args) {
12 |
13 | //Java 9
14 | LocalDate today = LocalDate.now();
15 | Stream next3Days = today.datesUntil(today.plusDays(3));
16 | next3Days.forEach(System.out::println);
17 |
18 | Stream sameDayNext3Weeks = today.datesUntil(today.plusDays(21),
19 | Period.ofWeeks(1));
20 | sameDayNext3Weeks.forEach(System.out::println);
21 |
22 | //Java 8
23 | Stream nextThreeDays = Stream.iterate(today, d -> d.plusDays(1));
24 | List dates = nextThreeDays
25 | .limit(3)
26 | .collect(Collectors.toList());
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/StreamOfRandomNumbers.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | import java.security.NoSuchAlgorithmException;
4 | import java.security.SecureRandom;
5 | import java.util.List;
6 | import java.util.Random;
7 | import java.util.stream.Collectors;
8 | import java.util.stream.DoubleStream;
9 | import java.util.stream.IntStream;
10 |
11 | public class StreamOfRandomNumbers {
12 | @SuppressWarnings("unused")
13 | public static void main(final String[] args) throws NoSuchAlgorithmException {
14 | Random random = new Random();
15 |
16 | //1
17 | IntStream randStream = random.ints(5);
18 | //randStream.forEach(System.out::println);
19 |
20 | //2
21 | DoubleStream doubleStream = random.doubles(5, 0, 0.5);
22 | //doubleStream.forEach(System.out::println);
23 |
24 | //collect to list
25 | List longs = random.longs(5)
26 | .boxed()
27 | .collect(Collectors.toList());
28 |
29 | SecureRandom sRand = SecureRandom.getInstanceStrong();
30 | randStream = random.ints(5);
31 | randStream.forEach(System.out::println);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/TeeingCollectorExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams;
2 |
3 | public class TeeingCollectorExample {
4 |
5 | public static void main(String[] args) {
6 |
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/conversions/IterableToStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.conversions;
2 |
3 | import java.util.Arrays;
4 | import java.util.stream.Stream;
5 | import java.util.stream.StreamSupport;
6 |
7 | public class IterableToStream
8 | {
9 | public static void main(String[] args)
10 | {
11 | //Iterable
12 | Iterable iterable = Arrays.asList("a", "b", "c");
13 |
14 | //Iterable -> Stream
15 | Stream stream = StreamSupport.stream(iterable.spliterator(), false);
16 |
17 | //Apply stream operations
18 | stream.forEach(System.out::println);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/conversions/IteratorToStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.conversions;
2 |
3 | import java.util.Arrays;
4 | import java.util.Iterator;
5 | import java.util.Spliterator;
6 | import java.util.Spliterators;
7 | import java.util.stream.Stream;
8 | import java.util.stream.StreamSupport;
9 |
10 | @SuppressWarnings("unused")
11 | public class IteratorToStream
12 | {
13 | public static void main(String[] args)
14 | {
15 | // Iterator
16 | Iterator iterator = Arrays.asList("a", "b", "c")
17 | .listIterator();
18 |
19 | //Works in Java 9 onwards
20 |
21 | Stream.generate(() -> null)
22 | .takeWhile(x -> iterator.hasNext())
23 | .map(n -> iterator.next())
24 | .forEach(System.out::println);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/distinct/DistinctPrimitivesAndStrings.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.distinct;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | public class DistinctPrimitivesAndStrings {
8 | public static void main(String[] args) {
9 | List list = Arrays.asList("A", "B", "C", "D", "A", "B", "C");
10 |
11 | // Get collection without duplicate i.e. distinct only
12 | List distinctItems =
13 | list.stream().distinct().collect(Collectors.toList());
14 |
15 | // Let's verify distinct elements
16 | System.out.println(distinctItems);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/intstream/FilterExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.intstream;
2 |
3 | import java.util.List;
4 | import java.util.function.IntPredicate;
5 | import java.util.stream.Collectors;
6 | import java.util.stream.IntStream;
7 |
8 | public class FilterExample
9 | {
10 | public static void main(String[] args)
11 | {
12 | IntStream stream = IntStream.range(1, 100);
13 |
14 | List primes = stream.filter(FilterExample::isPrime)
15 | .boxed()
16 | .collect(Collectors.toList());
17 |
18 | System.out.println(primes);
19 | }
20 |
21 | public static boolean isPrime(int i)
22 | {
23 | IntPredicate isDivisible = index -> i % index == 0;
24 | return i > 1 && IntStream.range(2, i).noneMatch(isDivisible);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/intstream/ForEachExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.intstream;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | public class ForEachExample
6 | {
7 | public static void main(String[] args)
8 | {
9 | //Normal loop
10 |
11 | for(int i=0; i < 5; i++)
12 | {
13 | doSomething(i);
14 | }
15 |
16 | //IntStream forEach
17 |
18 | IntStream.rangeClosed(0, 4)
19 | .forEach( ForEachExample::doSomething );
20 | }
21 |
22 | private static void doSomething(int i) {
23 | System.out.println(i);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/intstream/RangeExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.intstream;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | public class RangeExample
6 | {
7 | public static void main(String[] args)
8 | {
9 | //Range
10 | IntStream stream = IntStream.range(5, 10);
11 | stream.forEach( System.out::println ); //5,6,7,8,9
12 |
13 | //Closed Range
14 | IntStream closedRangeStream = IntStream.rangeClosed(5, 10);
15 | closedRangeStream.forEach( System.out::println ); //5,6,7,8,9,10
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/methods/ForEach.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.methods;
2 |
3 | import java.util.Arrays;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.function.Consumer;
7 |
8 | public class ForEach {
9 | public static void main(final String[] args) {
10 | List list = Arrays.asList(2, 4, 6, 8, 10);
11 | Consumer action = System.out::println;
12 |
13 | list.stream()
14 | .forEach(action);
15 |
16 | list.stream()
17 | .sorted(Comparator.reverseOrder())
18 | .forEach(action);
19 |
20 | // for-each loop
21 | for (Integer i : list) {
22 | System.out.println(i);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/predicates/TestPredicates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.predicates;
2 |
3 | import com.howtodoinjava.core.streams.Employee;
4 | import java.util.List;
5 | import java.util.function.BiPredicate;
6 | import java.util.function.Predicate;
7 |
8 | public class TestPredicates {
9 |
10 | public static void main(String[] args) {
11 | Predicate isAdult = e -> e.getAge() > 18;
12 | Predicate isMale = p -> p.getName().equalsIgnoreCase("M");
13 | Predicate isAdultAndMale = isAdult.and(isMale);
14 | Predicate isAdultOrMale = isAdult.or(isMale);
15 | Predicate isMinor = isAdult.negate();
16 |
17 | BiPredicate isAdultMale = (p1, p2) -> p1 > 18 && p2.equalsIgnoreCase("M");
18 |
19 | List employeeList = List.of();
20 |
21 | List maleEmployeeList = employeeList.stream().filter(isMale).toList();
22 | List adultMalesList = employeeList.stream()
23 | .filter(x -> isAdultMale.test(x.getAge(), x.getName()))
24 | .toList();
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/sort/DateOfBirthComparator.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.sort;
2 |
3 | import java.util.Comparator;
4 |
5 | import com.howtodoinjava.core.streams.Employee;
6 |
7 | public class DateOfBirthComparator implements Comparator {
8 |
9 | @Override
10 | public int compare(final Employee e1, final Employee e2) {
11 | if (e1.getDateOfBirth() == null && e2.getDateOfBirth() == null) {
12 | return 0;
13 | } else if(e1.getDateOfBirth() == null) {
14 | return -1;
15 | } else if(e2.getDateOfBirth() == null) {
16 | return 1;
17 | } else {
18 | return e1.getDateOfBirth().compareTo(e2.getDateOfBirth());
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/sort/FirstNameSorter.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.sort;
2 |
3 | import java.util.Comparator;
4 |
5 | import com.howtodoinjava.core.streams.Person;
6 |
7 | public class FirstNameSorter implements Comparator {
8 |
9 | @Override
10 | public int compare(final Person p1, final Person p2) {
11 | if (p1.fname() == null || p2.fname() == null) {
12 | throw new IllegalArgumentException(
13 | "Unnamed Person found in the system");
14 | }
15 | return p1.fname().compareToIgnoreCase(p2.fname());
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/sort/NumberStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.sort;
2 |
3 | import java.util.Comparator;
4 | import java.util.stream.Stream;
5 |
6 | public class NumberStream {
7 |
8 | public static void main(String[] args) {
9 | Stream numStream = Stream.of(1, 3, 5, 4, 2);
10 |
11 | numStream.sorted().forEach(System.out::println);
12 |
13 | // Recreated stream for demo purpose
14 | numStream = Stream.of(1, 3, 5, 4, 2);
15 |
16 | numStream.sorted(Comparator.reverseOrder())
17 | .forEach(System.out::println);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/streams/sort/StringStream.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.streams.sort;
2 |
3 | import java.util.Comparator;
4 | import java.util.stream.Stream;
5 |
6 | public class StringStream {
7 |
8 | public static void main(String[] args) {
9 | Stream wordStream = Stream.of("A", "C", "E", "B", "D");
10 |
11 | wordStream.sorted() // ascending
12 | .forEach(System.out::println);
13 |
14 | wordStream.sorted(Comparator.reverseOrder()) // descending
15 | .forEach(System.out::println);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Cancat.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class Cancat {
6 |
7 | public static void main(String[] args) {
8 |
9 | String str = "Hello";
10 | Assertions.assertEquals("Hello World", str.concat(" World"));
11 |
12 | Assertions.assertEquals("Hello", str.concat(""));
13 |
14 | Assertions.assertThrows(NullPointerException.class, ()->{
15 | str.concat(null);
16 | });
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/ChatAt.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class ChatAt {
6 |
7 | public static void main(String[] args) {
8 | String str = "howtodoinjava.com";
9 |
10 | Assertions.assertEquals('h', str.charAt(0));
11 |
12 | Assertions.assertEquals('m', str.charAt(str.length() - 1));
13 |
14 | Assertions.assertEquals('.', str.charAt(13));
15 |
16 | Assertions.assertThrows(StringIndexOutOfBoundsException.class, ()->{
17 | str.charAt(50);
18 | });
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/CompareTo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import static org.hamcrest.MatcherAssert.assertThat;
4 | import static org.hamcrest.Matchers.equalTo;
5 | import static org.hamcrest.Matchers.greaterThan;
6 | import static org.hamcrest.Matchers.lessThan;
7 |
8 | public class CompareTo {
9 | public static void main(String[] args) {
10 |
11 | String name = "alex";
12 |
13 | //same string
14 | assertThat(name.compareTo("alex"), equalTo(0));
15 |
16 | //Different cases
17 | assertThat(name.compareTo("Alex"), greaterThan(0));
18 | assertThat(name.compareTo("ALEX"), greaterThan(0));
19 |
20 | //Different strings
21 | assertThat(name.compareTo("alexa"), lessThan(0));
22 | assertThat(name.compareTo("ale"), greaterThan(0));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/CompareToIgnoreCase.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class CompareToIgnoreCase {
6 |
7 | public static void main(String[] args) {
8 |
9 | String name = "Alex";
10 |
11 | Assertions.assertEquals(0, name.compareToIgnoreCase("Alex"));
12 | Assertions.assertEquals(0, name.compareToIgnoreCase("alex"));
13 | Assertions.assertEquals(0, name.compareToIgnoreCase("ALEX"));
14 |
15 | Assertions.assertEquals(-1, name.compareToIgnoreCase("alexA"));
16 | Assertions.assertEquals(1, name.compareToIgnoreCase("ale"));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Contains.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class Contains {
6 |
7 | public static void main(String[] args) {
8 | Assertions.assertTrue("Hello World, Java!".contains("World"));
9 | Assertions.assertFalse("Hello World, Java!".contains("world"));
10 |
11 | Assertions.assertThrows(NullPointerException.class, () -> {
12 | "Hello World, Java!".contains(null);
13 | });
14 |
15 | Assertions.assertFalse("Hello World, Java!".contains("\\s"));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/EndsWith.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 |
4 | import org.junit.jupiter.api.Assertions;
5 |
6 | public class EndsWith {
7 |
8 | public static void main(String[] args) {
9 | String name = "howtodoinjava";
10 |
11 | Assertions.assertTrue(name.endsWith("java"));
12 | Assertions.assertFalse(name.endsWith("java$"));
13 |
14 | Assertions.assertThrows(NullPointerException.class, ()->{
15 | name.endsWith(null);
16 | });
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Equals.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class Equals {
6 |
7 | public static void main(String[] args) {
8 |
9 | String str1 = "alex";
10 | String str2 = "alex";
11 | String str3 = "alexa";
12 |
13 | Assertions.assertTrue(str1.equals(str2));
14 | Assertions.assertFalse(str1.equals(str3));
15 |
16 | Assertions.assertTrue(new String("alex").equals(new String("alex")));
17 |
18 | Assertions.assertThrows(NullPointerException.class, () -> {
19 | str1.contains(null);
20 | });
21 |
22 | Assertions.assertTrue(str1.equals("alex"));
23 | Assertions.assertFalse(str1.equals("Alex"));
24 |
25 | String strObj1 = new String("test");
26 | String strObj2 = new String("test");
27 |
28 | Assertions.assertFalse(strObj1 == strObj2);
29 | Assertions.assertTrue(strObj2.equals(strObj2));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/IndexOf.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class IndexOf {
6 |
7 | public static void main(String[] args) {
8 | String str = "Hello World";
9 |
10 | Assertions.assertEquals(6, str.indexOf("World"));
11 |
12 | Assertions.assertEquals(7, str.indexOf('o', 5));
13 |
14 | Assertions.assertThrows(NullPointerException.class, () -> {
15 | str.indexOf(null);
16 | });
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Intern.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class Intern {
6 |
7 | public static void main(String[] args) {
8 | String strObject = new String("Alex");
9 | String strLiteral = strObject.intern();
10 |
11 | Assertions.assertFalse(strObject == strLiteral);
12 | Assertions.assertTrue(strObject.equals(strLiteral));
13 |
14 | String newLiteral = "Alex";
15 | Assertions.assertTrue(strLiteral == newLiteral);
16 |
17 | String upperCased = "Alex123".toUpperCase();
18 | System.out.println(upperCased);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/LastIndexOf.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class LastIndexOf {
6 |
7 | public static void main(String[] args) {
8 | String str = "Hello world Java programmers, welcome to Java world !";
9 |
10 | Assertions.assertEquals(41, str.lastIndexOf("Java"));
11 | Assertions.assertEquals(41, str.lastIndexOf('J'));
12 |
13 | Assertions.assertEquals(12, str.lastIndexOf("Java", str.indexOf(",")));
14 | Assertions.assertEquals(12, str.lastIndexOf('J', str.indexOf(",")));
15 |
16 | Assertions.assertThrows(NullPointerException.class, ()->{
17 | str.lastIndexOf(null);
18 | });
19 |
20 | Assertions.assertEquals(str.length(), str.lastIndexOf(""));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Lowercase.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import java.util.Locale;
4 | import org.junit.jupiter.api.Assertions;
5 |
6 | public class Lowercase {
7 |
8 | public static void main(String[] args) {
9 | String name = "HowToDoInJava.com";
10 |
11 | Assertions.assertEquals("howtodoinjava.com", name.toLowerCase());
12 |
13 | System.out.println("howtodoinjava.com".toLowerCase(new Locale("tr", "TR")));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/java/com/howtodoinjava/core/string/README.md
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/Replace.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import java.util.regex.PatternSyntaxException;
4 | import java.util.stream.Stream;
5 | import org.junit.jupiter.api.Assertions;
6 |
7 | public class Replace {
8 |
9 | public static void main(String[] args) {
10 | String message = "Hello world !!";
11 |
12 | Assertions.assertEquals("HellO wOrld !!", message.replace('o', 'O'));
13 | Assertions.assertEquals("Hi world !!", message.replace("Hello", "Hi"));
14 |
15 | Assertions.assertEquals("Hello world !!", message.replace("[H]", "h"));
16 |
17 | Assertions.assertThrows(NullPointerException.class, () -> {
18 | message.replace(null, "O");
19 | });
20 |
21 | Assertions.assertThrows(NullPointerException.class, () -> {
22 | message.replace("o", null);
23 | });
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/ReplaceAll.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import java.util.regex.PatternSyntaxException;
4 | import org.junit.jupiter.api.Assertions;
5 |
6 | public class ReplaceAll {
7 |
8 | public static void main(String[] args) {
9 | String str = "how to do in java !! a java blog !!";
10 |
11 | Assertions.assertEquals("how to do in scala !! a scala blog !!",
12 | str.replaceAll("java", "scala"));
13 |
14 | String blog = "how to do in java";
15 |
16 | Assertions.assertEquals("howtodoinjava", blog.replaceAll("\\s", ""));
17 |
18 | Assertions.assertThrows(PatternSyntaxException.class, () -> {
19 | blog.replaceAll("[", "");
20 | });
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/ReplaceFirst.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | public class ReplaceFirst {
4 |
5 | public static void main(String[] args) {
6 | //simple string
7 | String str = "howtodoinjava";
8 | String newStr = str.replaceFirst("java", "JAVA");
9 | System.out.println(newStr); //howtodoinJAVA
10 |
11 | //regex
12 | String string = "how to do in java";
13 | String updatedString = string.replaceFirst("\\s", "-");
14 | System.out.println(updatedString); //how-to do in java
15 |
16 | //metacharacters
17 | String string2 = "how+to+do+in+java";
18 | String updatedString2 = string2.replaceFirst("\\+", "-");
19 | System.out.println(updatedString2); //how-to+do+in+java
20 |
21 | //null is not allowed
22 | String string1 = "how to do in java";
23 | //String updatedString1 = string1.replaceFirst(null, "-"); //Throws NullPointerException
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/ReverseString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class ReverseString {
6 |
7 | public static void main(String[] args) {
8 | String blogName = "How To Do In Java";
9 | String reverseString = reverseString(blogName);
10 |
11 | Assertions.assertEquals("avaJ nI oD oT woH", reverseString);
12 |
13 | reverseString = new StringBuilder(blogName).reverse().toString();
14 | Assertions.assertEquals("avaJ nI oD oT woH", reverseString);
15 |
16 | }
17 |
18 | public static String reverseString(String string) {
19 | if (string.isEmpty()) {
20 | return string;
21 | }
22 | return reverseString(string.substring(1)) + string.charAt(0);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/ReverseWords.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import java.util.Arrays;
4 | import java.util.stream.Collectors;
5 | import org.apache.commons.lang3.StringUtils;
6 | import org.junit.jupiter.api.Assertions;
7 |
8 | public class ReverseWords {
9 |
10 | public static void main(String[] args) {
11 | String input = "alex brian charles";
12 |
13 | //1 - Stream
14 | String reversed = Arrays.stream(input.split(" "))
15 | .map(word -> new StringBuilder(word).reverse())
16 | .collect(Collectors.joining(" "));
17 |
18 | System.out.println(reversed);
19 |
20 |
21 | //2 - StringUtils
22 | reversed = StringUtils.reverseDelimited(StringUtils.reverse(input), ' ');
23 | System.out.println(reversed);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/StringEquality.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class StringEquality {
6 |
7 | public static void main(String[] args) {
8 |
9 | Assertions.assertFalse("null".equalsIgnoreCase(null));
10 | Assertions.assertFalse("abc".equalsIgnoreCase("abcd")); //Different strings
11 |
12 | Assertions.assertTrue("abc".equalsIgnoreCase("ABC"));
13 | Assertions.assertTrue("ABC".equalsIgnoreCase("AbC"));
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/StringIndentExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | public class StringIndentExample {
4 |
5 | public static void main(String[] args) {
6 | String line1 = "ABC".indent(8);
7 | System.out.println(line1.replace(" ", "-"));
8 |
9 | String line2 = "ABC".indent(8).indent(-5);
10 | System.out.println(line2.replace(" ", "-"));
11 |
12 | String textBlock = """
13 | Line 1
14 | Line 2""";
15 |
16 | String indentedBlock = """
17 | Line 1
18 | Line 2""".indent(8);
19 |
20 | System.out.println(textBlock.replace(" ", "-"));
21 | System.out.println(indentedBlock.replace(" ", "-"));
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/core/string/SubString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.core.string;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 |
5 | public class SubString {
6 |
7 | public static void main(String[] args) {
8 | String str = "Hello World";
9 |
10 | Assertions.assertEquals("Hello", str.substring(0, 5));
11 | Assertions.assertEquals("llo Wo", str.substring(2, 8));
12 |
13 | Assertions.assertEquals("World", str.substring(6));
14 |
15 | Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
16 | str.substring(-1);
17 | });
18 |
19 | Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
20 | str.substring(6, 4);
21 | });
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/csv/demoOpenCSV/OpenCSVExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.csv.demoOpenCSV;
2 |
3 | import java.io.FileReader;
4 | import java.io.IOException;
5 |
6 | import com.opencsv.CSVReader;
7 |
8 | public class OpenCSVExample {
9 |
10 | public static void main(String[] args)
11 | {
12 | CSVReader reader = null;
13 | try
14 | {
15 | //Get the CSVReader instance with specifying the delimiter to be used
16 | reader = new CSVReader(new FileReader("C:\\Lokesh\\Setup\\workspace\\PlayingWithCSV\\src\\SampleCSVFile.csv"));
17 | String [] nextLine;
18 | //Read one line at a time
19 | while ((nextLine = reader.readNext()) != null)
20 | {
21 | for(String token : nextLine)
22 | {
23 | //Print all tokens
24 | System.out.println(token);
25 | }
26 | }
27 | }
28 | catch (Exception e) {
29 | e.printStackTrace();
30 | }
31 | finally {
32 | try {
33 | reader.close();
34 | } catch (IOException e) {
35 | e.printStackTrace();
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/csv/demoScanner/ScannerExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.csv.demoScanner;
2 |
3 | import java.io.File;
4 | import java.io.FileNotFoundException;
5 | import java.util.Scanner;
6 |
7 | public class ScannerExample
8 | {
9 | public static void main(String[] args) throws FileNotFoundException
10 | {
11 | //Get scanner instance
12 | Scanner scanner = new Scanner(new File("C:\\Lokesh\\Setup\\workspace\\PlayingWithCSV\\src\\SampleCSVFile.csv"));
13 |
14 | //Set the delimiter used in file
15 | scanner.useDelimiter(",");
16 |
17 | //Get all tokens and store them in some data structure
18 | //I am just printing them
19 | while (scanner.hasNext())
20 | {
21 | System.out.print(scanner.next() + "|");
22 | }
23 |
24 | //Do not forget to close the scanner
25 | scanner.close();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/datastructure/TestListImpl.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.datastructure;
2 |
3 | public class TestListImpl {
4 |
5 | public static void main(String[] args) {
6 | CustomList namesList = new CustomList<>();
7 |
8 | namesList.add("Lokesh");
9 | namesList.add("Alex");
10 |
11 | System.out.println(namesList); //[Lokesh,Alex]
12 |
13 | System.out.println(namesList.get(0)); //Lokesh
14 |
15 | namesList.remove(1);
16 |
17 | System.out.println(namesList); //[Lokesh]
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/datastructure/TestStackImpl.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.datastructure;
2 |
3 | public class TestStackImpl {
4 |
5 | public static void main(String[] args) {
6 | Stack stack = new Stack(5);
7 |
8 | stack.push(1);
9 | stack.push(2);
10 | stack.push(3);
11 | stack.push(4);
12 | stack.push(5);
13 |
14 | System.out.println(stack);
15 |
16 | stack.push(6);
17 |
18 | stack.pop();
19 |
20 | System.out.println(stack);
21 |
22 | stack.push(6);
23 |
24 | System.out.println(stack);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/exercise/ArrayTwoSum.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.exercise;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | public class ArrayTwoSum {
8 |
9 | public static void main(String[] args) {
10 | int[] nums = new int[]{2, 7, 11, 15};
11 | int target = 9;
12 |
13 | int[] output = twoSum(nums, target);
14 | System.out.println(Arrays.toString(output)); //[0, 1]
15 | }
16 |
17 | public static int[] twoSum(int[] nums, int target) {
18 |
19 | Map map = new HashMap<>();
20 | for (int i = 0; i < nums.length; i++) {
21 |
22 | int complement = target - nums[i];
23 | if (map.containsKey(complement)) {
24 | return new int[]{map.get(complement), i};
25 | }
26 | map.put(nums[i], i);
27 | }
28 | return new int[]{};
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/hashing/password/demo/bcrypt/BcryptHashingExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.hashing.password.demo.bcrypt;
2 |
3 | import java.security.NoSuchAlgorithmException;
4 |
5 | public class BcryptHashingExample {
6 | public static void main(String[] args) throws NoSuchAlgorithmException {
7 | String originalPassword = "password";
8 | String generatedSecuredPasswordHash = BCrypt.hashpw(originalPassword, BCrypt.gensalt(12));
9 | System.out.println(generatedSecuredPasswordHash);
10 |
11 | boolean matched = BCrypt.checkpw(originalPassword, generatedSecuredPasswordHash);
12 | System.out.println(matched);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/hashing/password/demo/scrypt/ScryptPasswordHashingDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.hashing.password.demo.scrypt;
2 |
3 | import com.lambdaworks.crypto.SCryptUtil;
4 |
5 | public class ScryptPasswordHashingDemo {
6 | public static void main(String[] args) {
7 | String originalPassword = "password";
8 | String generatedSecuredPasswordHash = SCryptUtil.scrypt(originalPassword, 16, 16, 16);
9 | System.out.println(generatedSecuredPasswordHash);
10 |
11 | boolean matched = SCryptUtil.check("password", generatedSecuredPasswordHash);
12 | System.out.println(matched);
13 |
14 | boolean unmatched = SCryptUtil.check("diff_password", generatedSecuredPasswordHash);
15 | System.out.println(unmatched);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/CheckEmptyDirectory.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.DirectoryStream;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 |
10 | public class CheckEmptyDirectory {
11 | public static void main(String[] args) throws IOException {
12 |
13 | Path dirPath = Paths.get("C:/temp");
14 |
15 | //1
16 | boolean isEmptyDirectory = Files.list(dirPath)
17 | .findAny()
18 | .isPresent();
19 |
20 | //2
21 | if (Files.isDirectory(dirPath)) {
22 | try (DirectoryStream dirStream =
23 | Files.newDirectoryStream(dirPath)) {
24 | isEmptyDirectory = !dirStream.iterator().hasNext();
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/CheckIfFileExists.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 |
8 | public class CheckIfFileExists {
9 | public static void main(final String[] args) throws IOException {
10 | //1
11 | File tempFile = new File("c:/temp/temp.txt");
12 | boolean exists = tempFile.exists();
13 |
14 | //2
15 | final Path path = Files.createTempFile("testFile", ".txt");
16 | Files.exists(path); //true
17 |
18 | Path tempDirectory = Files.createTempDirectory("temp-dir");
19 | exists = Files.exists(tempDirectory);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/ConvertReaderToString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | public class ConvertReaderToString {
4 | public static void main(String[] args) {
5 |
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/CountFileLines.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import org.apache.commons.io.FileUtils;
4 |
5 | import java.io.File;
6 | import java.io.FileReader;
7 | import java.io.IOException;
8 | import java.io.LineNumberReader;
9 | import java.nio.file.Files;
10 | import java.nio.file.Paths;
11 | import java.util.List;
12 | import java.util.stream.Stream;
13 |
14 | public class CountFileLines {
15 | public static void main(String[] args) throws IOException {
16 | String fileName = "c:/temp";
17 | long noOfLines = -1;
18 |
19 | //1
20 | try (Stream fileStream = Files.lines(Paths.get(fileName))) {
21 | noOfLines = (int) fileStream.count();
22 | }
23 |
24 | //2
25 | List lines = Files.readAllLines(Paths.get(fileName));
26 | noOfLines = lines.size();
27 |
28 | //3
29 | try(LineNumberReader lineNumberReader =
30 | new LineNumberReader(new FileReader(new File(fileName)))) {
31 | lineNumberReader.skip(Long.MAX_VALUE);
32 | noOfLines = lineNumberReader.getLineNumber() + 1;
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/CreateDirectory.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 | import java.nio.file.Paths;
8 |
9 | public class CreateDirectory {
10 | public static void main(String[] args) throws IOException {
11 | String dirName = "c:/temp/data";
12 | Path path = Paths.get(dirName);
13 |
14 | //1
15 | if (!Files.exists(path)) {
16 | Files.createDirectory(path);
17 | }
18 |
19 | Files.createDirectories(path);
20 |
21 | //2
22 | File newDir = new File("c:/temp/data");
23 | if(!newDir.exists()) {
24 | boolean isDirectoryCreated = newDir.mkdir();
25 | }
26 |
27 | boolean isDirectoryCreated = newDir.mkdirs();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/CreateTempFile.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 | import java.nio.file.Path;
7 |
8 | public class CreateTempFile {
9 | public static void main(final String[] args) {
10 | //1
11 | File temp;
12 | try
13 | {
14 | temp = File.createTempFile("testData", ".txt");
15 | System.out.println("Temp file created : " + temp.getAbsolutePath());
16 | }
17 | catch (IOException e)
18 | {
19 | e.printStackTrace();
20 | }
21 |
22 | //2
23 | try
24 | {
25 | final Path path = Files.createTempFile("myTempFile", ".txt");
26 | System.out.println("Temp file : " + path);
27 |
28 | //Delete file on exit
29 | path.toFile().deleteOnExit();
30 |
31 | } catch (IOException e)
32 | {
33 | e.printStackTrace();
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/DeleteAFile.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import org.apache.commons.io.FileUtils;
4 |
5 | import java.io.File;
6 | import java.io.IOException;
7 | import java.nio.file.Files;
8 | import java.nio.file.Path;
9 |
10 |
11 | public class DeleteAFile {
12 | public static void main(String[] args) throws IOException {
13 | File file = new File("c:/temp/one.txt");
14 |
15 | //1 File
16 | boolean deleted = file.delete();
17 | file.deleteOnExit();
18 |
19 | //2 Files
20 | Path path = Path.of("c:/temp/one.txt");
21 | Files.delete(path);
22 |
23 | Path path2 = Path.of("c:/temp/two.txt");
24 | Files.deleteIfExists(path);
25 |
26 | //3 FileUtils
27 | FileUtils.delete(file);
28 |
29 | FileUtils.deleteQuietly(new File("c:/temp"));
30 |
31 | FileUtils.deleteDirectory(new File("c:/temp"));
32 |
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/FileFilterExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.FileFilter;
5 | import java.io.FilenameFilter;
6 |
7 | public class FileFilterExample {
8 | public static void main(String[] args)
9 | {
10 | File directory = new File("c:/temp");
11 |
12 | //Verify if it is a valid file name
13 | if (!(directory.exists() && directory.isDirectory()))
14 | {
15 | System.out.println(String.format("Directory %s does not exist", directory));
16 | return;
17 | }
18 |
19 | FileFilter logFilefilter = new FileFilter() {
20 | public boolean accept(File file) {
21 | if (file.getName().endsWith(".log")) {
22 | return true;
23 | }
24 | return false;
25 | }
26 | };
27 |
28 | /*FileFilter logFileFilter = (file) -> {
29 | return file.getName().endsWith(".log");
30 | };*/
31 |
32 | File[] files = directory.listFiles(logFilefilter);
33 |
34 | for (File f: files)
35 | {
36 | System.out.println(f.getName());
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/FilePath.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Path;
6 |
7 | public class FilePath {
8 | public static void main(String[] args) throws IOException {
9 | File file = new File("com/howtodoinjava/io/foo/bar/../foo.txt");
10 |
11 | //1
12 | String givenPath = file.getPath();
13 | String absPath = file.getAbsolutePath();
14 | String canPath = file.getCanonicalPath();
15 |
16 | System.out.println(givenPath);
17 | System.out.println(absPath);
18 | System.out.println(canPath);
19 |
20 | //2
21 | Path path = Path.of("com/howtodoinjava/io/foo/bar/../foo.txt");
22 |
23 | givenPath = path.toString();
24 | absPath = path.toAbsolutePath().toString();
25 | canPath = path.toRealPath().toString();
26 |
27 | System.out.println(givenPath);
28 | System.out.println(absPath);
29 | System.out.println(canPath);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/FileSize.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.file.Files;
6 |
7 | import org.apache.commons.io.FileUtils;
8 |
9 | public class FileSize {
10 | public static void main(final String[] args) throws IOException {
11 | File file = new File("c:/temp/demo.txt");
12 |
13 | //1
14 | long bytes = Files.size(file.toPath());
15 |
16 | System.out.println(String.format("%,d Bytes", bytes));
17 | System.out.println(String.format("%,d KB", bytes / 1024));
18 |
19 | //2
20 | bytes = file.length();
21 | System.out.println(String.format("%,d Bytes", bytes));
22 |
23 | //3
24 | bytes = FileUtils.sizeOf(file);
25 | System.out.println(String.format("%,d Bytes", bytes));
26 |
27 | String displaySize = FileUtils.byteCountToDisplaySize(bytes);
28 | System.out.println(displaySize);
29 |
30 | System.out.println(FileUtils.byteCountToDisplaySize(2333444l)); //2 MB
31 | System.out.println(FileUtils.byteCountToDisplaySize(2333444555l)); //2 GB
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/FileWriterExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.FileWriter;
5 | import java.io.IOException;
6 |
7 | public class FileWriterExample
8 | {
9 | public static void main(String[] args)
10 | throws IOException
11 | {
12 | String fileName = "dataOut.txt";
13 |
14 | //1
15 | try (FileWriter fw
16 | = new FileWriter(new File(fileName))) {
17 |
18 | fw.write("humpty dumpty");
19 | }
20 |
21 | //2
22 | try (FileWriter fw
23 | = new FileWriter(new File(fileName), true)) {
24 |
25 | fw.append(" sat on a wall");
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/InputStreamReaderExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.FileInputStream;
4 | import java.io.InputStreamReader;
5 |
6 | public class InputStreamReaderExample
7 | {
8 | public static void main(String[] args)
9 | {
10 | //1
11 |
12 | try (InputStreamReader input
13 | = new InputStreamReader(new FileInputStream("demo.txt"))) {
14 |
15 | // Creates an array of character
16 | char[] array = new char[50];
17 |
18 | // Reads characters from the file
19 | input.read(array);
20 |
21 | System.out.println(array);
22 | }
23 | catch (Exception e) {
24 | e.getStackTrace();
25 | }
26 |
27 | //2
28 | try (InputStreamReader input
29 | = new InputStreamReader(new FileInputStream("demo.txt"))) {
30 |
31 | int data = input.read();
32 | while (data != -1) {
33 | System.out.print((char) data);
34 | data = input.read();
35 | }
36 | }
37 | catch (Exception e) {
38 | e.getStackTrace();
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/ReadFileToByteArray.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.io.IOException;
6 | import java.nio.file.Files;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 | import java.util.ArrayList;
10 | import java.util.Collections;
11 | import org.apache.commons.io.FileUtils;
12 | import org.apache.commons.io.IOUtils;
13 |
14 | public class ReadFileToByteArray {
15 |
16 | public static void main(String[] args) throws IOException {
17 | Path path = Paths.get("C:/temp/test.txt");
18 | File file = new File("C:/temp/test.txt");
19 |
20 | //1
21 | byte[] data = Files.readAllBytes(path);
22 |
23 | //2
24 | byte[] bytes = new byte[(int) file.length()];
25 | try(FileInputStream fis = new FileInputStream(file)) {
26 | fis.read(bytes);
27 | }
28 |
29 | //3
30 | byte[] bytes1 = FileUtils.readFileToByteArray(file);
31 | byte[] bytes2 = IOUtils.toByteArray(new FileInputStream(file));
32 |
33 | //4
34 | byte[] bytes3 = com.google.common.io.Files.toByteArray(file);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/ReadGivenLineFromFile.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
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.Collections;
8 | import java.util.List;
9 | import java.util.stream.Stream;
10 |
11 | public class ReadGivenLineFromFile {
12 | public static void main(String[] args) {
13 | Path filePath = Paths.get("C:/temp/file.txt");
14 |
15 | //1
16 | List lines = null;
17 | try {
18 | lines = Collections.unmodifiableList(Files.readAllLines(filePath));
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 |
23 | //Read second line
24 | String secondLine = lines.get(1);
25 |
26 | //2
27 | //try-with-resources
28 | try (Stream streamOfLines = Files.lines( filePath ))
29 | {
30 | String secondLines = streamOfLines.skip(1)
31 | .findFirst()
32 | .get();
33 | }
34 | catch (IOException e)
35 | {
36 | e.printStackTrace();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/ReadLargeFiles.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import org.apache.commons.io.FileUtils;
4 | import org.apache.commons.io.LineIterator;
5 |
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.nio.file.Files;
9 | import java.nio.file.Paths;
10 | import java.util.stream.Stream;
11 |
12 | public class ReadLargeFiles {
13 | public static void main(String[] args) {
14 | //1
15 | File file = new File("C:/temp/file.txt");
16 |
17 | try(LineIterator it = FileUtils.lineIterator(file, "UTF-8")) {
18 | while (it.hasNext()) {
19 | String line = it.nextLine();
20 | // do something with line
21 | System.out.println(line);
22 | }
23 | } catch (IOException e) {
24 | e.printStackTrace();
25 | }
26 |
27 |
28 | //2
29 | try (Stream lines = Files.lines(Paths.get("C:/temp/file.txt"))) {
30 | lines.forEach(line -> {
31 | // do something with line
32 | System.out.println(line);
33 | });
34 | } catch (IOException e) {
35 | e.printStackTrace();
36 | }
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/ReadOnlyFile.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.File;
4 |
5 | public class ReadOnlyFile {
6 | @SuppressWarnings("unused")
7 | public static void main(final String[] args) {
8 | File file = new File("c:/temp/testReadOnly.txt");
9 |
10 | // Mark it read only
11 | boolean success = file.setReadOnly();
12 |
13 | // Mark it read only
14 | success = file.setWritable(false);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/StringReaderExample.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import java.io.IOException;
4 | import java.io.StringReader;
5 |
6 | public class StringReaderExample
7 | {
8 | public static void main(String[] args) throws IOException
9 | {
10 | String data = "humpty dumpty";
11 | try (StringReader stringReader
12 | = new StringReader(data))
13 | {
14 | int ch = stringReader.read();
15 | while (ch != -1)
16 | {
17 | // do something with read char
18 | System.out.print((char)ch);
19 | ch = stringReader.read();
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/SymbolicLinkExamples.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
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 SymbolicLinkExamples {
9 | public static void main(String[] args) throws IOException {
10 | Path target = Paths.get("c:/temp/data.txt");
11 | Path link = Paths.get("c:/temp/links/data_link.txt");
12 |
13 | //1
14 | if (Files.exists(link)) {
15 | Files.delete(link);
16 | }
17 | Files.createSymbolicLink(link, target);
18 |
19 | //2
20 | boolean isLink = Files.isSymbolicLink(link); //true
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/WriteByteArrayToFile.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.io;
2 |
3 | import org.apache.commons.io.FileUtils;
4 |
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.nio.charset.StandardCharsets;
9 | import java.nio.file.Files;
10 | import java.nio.file.Path;
11 | import java.nio.file.Paths;
12 |
13 | public class WriteByteArrayToFile {
14 | public static void main(String[] args) throws IOException {
15 |
16 | byte[] bytes = "testData".getBytes();
17 | File file = new File("test.txt");
18 |
19 | //1
20 | Path filePath = Paths.get("/path/file");
21 | Files.write(filePath, bytes);
22 |
23 | //2
24 | try (FileOutputStream fos = new FileOutputStream("/path/file")) {
25 | fos.write(bytes);
26 | }
27 |
28 | //3
29 | FileUtils.writeByteArrayToFile(file, bytes);
30 |
31 | //4
32 | com.google.common.io.Files.write(bytes, file);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/foo/bar/bar.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/java/com/howtodoinjava/io/foo/bar/bar.txt
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/io/foo/foo.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/java/com/howtodoinjava/io/foo/foo.txt
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/mail/MailTest.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.mail;
2 |
3 | import java.util.List;
4 |
5 | public class MailTest {
6 |
7 | public static void main(String[] args) {
8 |
9 | EmailSender.sendPlainTextEmail("sender@gmail.in",
10 | "receiver@gmail.com",
11 | "Test Email",
12 | List.of("Hello", "World"),
13 | true);
14 |
15 | /*EmailSenderWithSSL.sendPlainTextEmail("admin@eprindia.in",
16 | "lokeshgupta1981@gmail.com",
17 | "Test Email",
18 | List.of("Hello", "World"),
19 | true);*/
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/misc/JFrameDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.misc;
2 |
3 | import javax.swing.*;
4 |
5 | public class JFrameDemo {
6 |
7 | public static void main(String args[]){
8 | JFrame jf = new JFrame("Hi");
9 | jf.setVisible(true);
10 | jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11 | System.out.println("Hi");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/misc/UnitTuple.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.misc;
2 |
3 | import org.javatuples.Pair;
4 | import org.javatuples.Unit;
5 |
6 | public class UnitTuple {
7 |
8 | public static void main(final String[] args) {
9 | Unit unit = new Unit<>("Sajal");
10 | System.out.println(unit.getValue0());
11 | Pair pair = unit.add(new Unit<>("Lokesh"));
12 | System.out.println(unit.getSize());
13 | System.out.println(unit.getValue0());
14 | System.out.println(pair.getValue1());
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/newFeatures/java21/README.md:
--------------------------------------------------------------------------------
1 | # Java 21 Tutorials
2 |
3 | - [Java 21 Unnamed Patterns and Variables (with Examples)](https://howtodoinjava.com/java/unnamed-patterns-and-variables/)
4 | - [Java 21 Scoped Values: A Deep Dive with Examples](https://howtodoinjava.com/java/multi-threading/java-scoped-values/)
5 | - [Java Record Patterns and Pattern Matching](https://howtodoinjava.com/java/record-patterns-and-pattern-matching/)
6 | - [Java Unnamed Classes and Instance Main Methods](https://howtodoinjava.com/java/java-unnamed-class-instance-method/)
7 | - [Java 21 Sequenced Collections](https://howtodoinjava.com/java/sequenced-collections/)
8 | - [Java 21 Features: Practical Examples and Insights](https://howtodoinjava.com/java/java-21-new-features/)
9 | - [Java 21 String Templates](https://howtodoinjava.com/java/java-string-templates/)
10 | - [Java 21 Structured Concurrency: StructuredTaskScope](https://howtodoinjava.com/java/multi-threading/structured-concurrency/)
11 | - [Java Virtual Threads – Project Loom](https://howtodoinjava.com/java/multi-threading/virtual-threads/)
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/newFeatures/java21/StringTemplates.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.newFeatures.java21;
2 |
3 | public class StringTemplates {
4 |
5 | public static void main(String[] args) {
6 | String name = "Alex";
7 | String message = STR."Greetings \{name}!";
8 | System.out.println(message);
9 |
10 | /*//FMT
11 | message = FMT."Greetings %-12s\{name}.";
12 |
13 | //RAW
14 | StringTemplate st = RAW."Greetings \{name}.";
15 | String message = STR.process(st);*/
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/newFeatures/java21/UnnamedClassAndInstanceMainMethod.java:
--------------------------------------------------------------------------------
1 | void main() {
2 | System.out.println("Hello, World!");
3 | }
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/newFeatures/java21/UnnamedVariables.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.newFeatures.java21;
2 |
3 | import java.util.PriorityQueue;
4 | import java.util.Queue;
5 |
6 | public class UnnamedVariables {
7 |
8 | void main() {
9 |
10 | //1
11 | Queue q = new PriorityQueue<>();
12 | q.add("1");
13 |
14 | String _ = q.remove();
15 |
16 | //2
17 | String input = "Hello, World!";
18 |
19 | try {
20 | int i = Integer.parseInt(input);
21 | // use i
22 | } catch (NumberFormatException _) {
23 | System.out.println("Invalid input: " + input);
24 | }
25 |
26 | //3
27 | int[] arr = new int[] {0,1,2,3,4};
28 | for (int i = 0, _ = runOnce(); i < arr.length; i++) {
29 | // use arr[i];
30 | // ... code that uses 'i' ...
31 | }
32 | }
33 |
34 | private static int runOnce() {
35 | //Some initialization code
36 | return -1;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/Anagram.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Arrays;
4 |
5 | public class Anagram {
6 |
7 | public static void main(String[] args) {
8 | String str1 = "listen";
9 | String str2 = "silent";
10 |
11 | System.out.println(checkAnagrams(str1, str2));
12 | }
13 |
14 | private static boolean checkAnagrams(String str1, String str2) {
15 |
16 | if (str1.length() != str2.length()) {
17 | return false;
18 | }
19 |
20 | char[] charArray1 = str1.toCharArray();
21 | char[] charArray2 = str2.toCharArray();
22 | Arrays.sort(charArray1);
23 | Arrays.sort(charArray2);
24 |
25 | return Arrays.equals(charArray1, charArray2);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/ArrayRotation.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Arrays;
4 |
5 | public class ArrayRotation {
6 | public static void main(String[] args) {
7 | int[] array = {1, 2, 3, 4, 5};
8 | int k = 2;
9 |
10 | System.out.println("Original Array: " + Arrays.toString(array));
11 |
12 | rotateArray(array, k);
13 |
14 | System.out.println("Rotated Array: " + Arrays.toString(array));
15 | }
16 |
17 | public static void rotateArray(int[] array, int k) {
18 | if (array == null || array.length == 0) {
19 | return;
20 | }
21 |
22 | int n = array.length;
23 | k = k % n; // Adjust k if it is greater than n
24 |
25 | reverseArray(array, 0, n - 1); // Reverse the entire array
26 | reverseArray(array, 0, k - 1); // Reverse the first k elements
27 | reverseArray(array, k, n - 1); // Reverse the remaining n-k elements
28 | }
29 |
30 | public static void reverseArray(int[] array, int start, int end) {
31 |
32 | while (start < end) {
33 | int temp = array[start];
34 | array[start] = array[end];
35 | array[end] = temp;
36 | start++;
37 | end--;
38 | }
39 | }
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/BalancedParenthesesChecker.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Stack;
4 |
5 | public class BalancedParenthesesChecker {
6 |
7 | public static void main(String[] args) {
8 | String expression1 = "{[ a; ( b; ) c; ]}";
9 | String expression2 = "{[ a; ( b; ) c; }]"; //incorrectly matched in last two characters
10 |
11 | checkBalancedParentheses(expression1); //true
12 | checkBalancedParentheses(expression2); //false
13 | }
14 |
15 | public static boolean checkBalancedParentheses(String expression) {
16 | Stack stack = new Stack<>();
17 |
18 | for (char ch : expression.toCharArray()) {
19 | if (ch == '(' || ch == '{' || ch == '[') {
20 | stack.push(ch);
21 | } else if (ch == ')' || ch == '}' || ch == ']') {
22 |
23 | if (stack.isEmpty()) {
24 | return false;
25 | }
26 |
27 | char top = stack.pop();
28 | if ((ch == ')' && top != '(') ||
29 | (ch == '}' && top != '{') ||
30 | (ch == ']' && top != '[')) {
31 | return false;
32 | }
33 | }
34 | }
35 | return stack.isEmpty();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/CommonElementsInArrays.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | public class CommonElementsInArrays {
8 |
9 | public static void main(String[] args) {
10 |
11 | Integer[][] arrays = {
12 | {1, 2, 3, 4, 5},
13 | {2, 4, 6, 8},
14 | {2, 3, 4, 7},
15 | {4, 5, 8, 9}
16 | };
17 |
18 | List commonElements = findCommonElements(arrays);
19 | System.out.println("Common elements in the arrays: " + commonElements);
20 | }
21 |
22 | public static List findCommonElements(Integer[][] arrays) {
23 | if (arrays == null || arrays.length == 0) {
24 | return List.of(); //empty arguments
25 | }
26 |
27 | List commonElements = Arrays.asList(arrays[0]);
28 |
29 | for (int i = 1; i < arrays.length; i++) {
30 | List temp = new ArrayList<>();
31 | for (int num : arrays[i]) {
32 | if (commonElements.contains(num)) {
33 | temp.add(num);
34 | }
35 | }
36 | commonElements = temp;
37 | }
38 | return commonElements;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/FindAllDuplicateNumbers.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import org.apache.commons.collections.MultiHashMap;
6 | import org.apache.commons.collections.MultiMap;
7 |
8 | public class FindAllDuplicateNumbers {
9 |
10 | public static void main(String[] args) {
11 | Integer[] array = {1, 2, 3, 2, 4, 3, 5, 6, 5, 7, 8, 8, 9};
12 |
13 | //1
14 | MultiMap multiMap = new MultiHashMap();
15 | for (int num : array) {
16 | multiMap.put(num, num);
17 | }
18 |
19 | List duplicates = multiMap.keySet().stream()
20 | .filter(i -> ((ArrayList) multiMap.get(i)).size() > 1)
21 | .toList();
22 |
23 | System.out.println(duplicates);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/FindMissingNumberFromSeries.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Arrays;
4 |
5 | public class FindMissingNumberFromSeries {
6 |
7 | public static void main(String[] args) {
8 | int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12};
9 |
10 | int N = numbers[numbers.length-1]; //The last element in the array
11 | int expectedSum = (N * (N + 1)) / 2;
12 | int actualSum = Arrays.stream(numbers).sum();
13 |
14 | int missingNumber = expectedSum - actualSum;
15 | System.out.println(missingNumber);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/FizzBuzz.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | public class FizzBuzz {
6 |
7 | public static void main(String[] args) {
8 |
9 | int end = 100;
10 |
11 | //Java 8 Streams
12 |
13 | IntStream.rangeClosed(1, end)
14 | .mapToObj(i -> i % 5 == 0 ? (i % 7 == 0 ? "FizzBuzz" : "Fizz") : (i % 7 == 0 ? "Buzz" : i))
15 | .forEach(System.out::println);
16 |
17 | //Java 7
18 |
19 | for (int i = 1; i <= end; i++) {
20 | if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
21 | {
22 | System.out.println("fizzbuzz");
23 | } else if ((i % 5) == 0) // Is it a multiple of 5?
24 | {
25 | System.out.println("fizz");
26 | } else if ((i % 7) == 0) // Is it a multiple of 7?
27 | {
28 | System.out.println("buzz");
29 | } else {
30 | System.out.println(i); // Not a multiple of 5 or 7
31 | }
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/GoodStringBadString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | public class GoodStringBadString {
4 |
5 | public static void main(String[] args) {
6 | String input = "Good Oops, Bad Oops";
7 |
8 | //1 Regex
9 | String output = input.replaceAll("(?i)(\\p{L})\\1", "$1");
10 | System.out.println(output);
11 |
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/IdentifyProblemsInCode.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | public class IdentifyProblemsInCode {
4 |
5 | public void howToDoInJava_method1() {
6 | System.out.println("how to do");
7 | return;
8 | //System.out.println("in java");
9 | }
10 |
11 | public void howToDoInJava_method2() {
12 | System.out.println("how to do");
13 | if (true) {
14 | return;
15 | }
16 | System.out.println("in java");
17 | }
18 |
19 | public void howToDoInJava_method3() {
20 | System.out.println("how to do");
21 | while (true) {
22 | return;
23 | }
24 | //System.out.println("in java");
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/LargestElementFinder.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | public class LargestElementFinder {
4 |
5 | public static void main(String[] args) {
6 | int[] array = {10, 20, 30, 40, 90, 23, 12, 60};
7 |
8 | int largest = findLargestElement(array);
9 | System.out.println("The largest element in the array is: " + largest);
10 | }
11 |
12 | public static int findLargestElement(int[] array) {
13 | if (array == null || array.length == 0) {
14 | throw new IllegalArgumentException("Array is empty or null.");
15 | }
16 |
17 | int largest = array[0];
18 |
19 | for (int i = 1; i < array.length; i++) {
20 | if (array[i] > largest) {
21 | largest = array[i];
22 | }
23 | }
24 |
25 | return largest;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/LongestSubstringLength.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class LongestSubstringLength {
7 |
8 | public static void main(String[] args) {
9 |
10 | String input = "abcabcbb";
11 | int length = findLongestSubstringLength(input);
12 |
13 | System.out.println(length); //3
14 | }
15 |
16 | public static int findLongestSubstringLength(String str) {
17 |
18 | int maxLength = 0;
19 | int left = 0;
20 | int right = 0;
21 | Set slidingWindow = new HashSet<>();
22 |
23 | while (right < str.length()) {
24 |
25 | char currentChar = str.charAt(right);
26 |
27 | if (slidingWindow.contains(currentChar)) {
28 | slidingWindow.remove(str.charAt(left));
29 | left++;
30 | } else {
31 | slidingWindow.add(currentChar);
32 | maxLength = Math.max(maxLength, right - left + 1);
33 | right++;
34 | }
35 | }
36 |
37 | return maxLength;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/MapPutOperation.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Map;
4 | import java.util.TreeMap;
5 |
6 | public class MapPutOperation {
7 |
8 | public static void main(String[] args) {
9 |
10 | Map map = new TreeMap<>();
11 | map.put("test key 1", "test value 1");
12 | map.put("test key 2", "test value 2");
13 | map.put("test key 3", "test value 3");
14 |
15 | //Predict the output
16 | System.out.println(map.put("test key 3", "test value 3"));
17 | System.out.println(map.put("test key 4", "test value 4"));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/NthLongestStringAlgorithm.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.TreeMap;
6 |
7 | public class NthLongestStringAlgorithm {
8 |
9 | public static void main(String[] args) {
10 | List list = List.of("Yuri", "Ron", "Interview", "Longest", "List", "Contain");
11 |
12 | for(int i=1; i<=4; i++){
13 | System.out.println("Words with " + i + "th length: " + findNthLongestElement(list, i));
14 | }
15 | }
16 |
17 | private static List findNthLongestElement(List list, int n) {
18 | if (n < 1) {
19 | return null; //Handle invalid case
20 | }
21 |
22 | TreeMap> map = new TreeMap<>();
23 |
24 | for (String str : list) {
25 | Integer length = str.length();
26 | List tempList = map.get(length) != null ? map.get(length) : new ArrayList();
27 | tempList.add(str);
28 | map.put(length, tempList);
29 | }
30 | return map.get(map.descendingKeySet().toArray()[n - 1]);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/PlayHiLoGame.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.io.IOException;
4 |
5 | public class PlayHiLoGame {
6 |
7 | public static void main(String[] args) {
8 |
9 | HiLo hiLo = new HiLo();
10 | try {
11 | hiLo.start();
12 | } catch (IOException e) {
13 | e.printStackTrace();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/ReverseAString.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | public class ReverseAString {
4 |
5 | public static void main(String[] args) {
6 | String string = "howtodoinjava";
7 | String reverseString = reverse(string);
8 | System.out.println(reverseString);
9 | }
10 |
11 | private static String reverse(String str) {
12 |
13 | char[] chars = str.toCharArray();
14 | int start = 0;
15 | int end = chars.length - 1;
16 |
17 | while (start < end) {
18 | // Swap characters at start and end indices
19 | char temp = chars[start];
20 | chars[start] = chars[end];
21 | chars[end] = temp;
22 |
23 | // Move the indices towards the center
24 | start++;
25 | end--;
26 | }
27 |
28 | return new String(chars);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/puzzles/TwoSum.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.puzzles;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | public class TwoSum {
8 |
9 | public static void main(String[] args) {
10 | int[] nums = {2, 7, 11, 18};
11 | int sum = 9;
12 |
13 | int[] result = twoSum(nums, sum);
14 | System.out.println(Arrays.toString(result));
15 | }
16 |
17 | private static int[] twoSum(int[] nums, int sum) {
18 |
19 | for (int i = 0; i < nums.length; i++) {
20 | int complement = sum - nums[i];
21 | int foundAtIndex = Arrays.binarySearch(nums, complement);
22 |
23 | if(foundAtIndex > 0) {
24 | return new int[] {nums[i], nums[foundAtIndex]};
25 | }
26 | }
27 | return null;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/regex/MaxMinLength.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.regex;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.regex.Matcher;
6 | import java.util.regex.Pattern;
7 |
8 | public class MaxMinLength {
9 |
10 | public static void main(String[] args) {
11 |
12 | List names = List.of("LOKESH", "JAVACRAZY", "LOKESHGUPTAINDIA", "LOKESH123");
13 |
14 | String regex = "^[A-Z]{1,10}$";
15 |
16 | Pattern pattern = Pattern.compile(regex);
17 |
18 | for (String name : names) {
19 | Matcher matcher = pattern.matcher(name);
20 | System.out.println(matcher.matches());
21 | }
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/regex/Misspelling.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.regex;
2 |
3 | import java.util.regex.Matcher;
4 | import java.util.regex.Pattern;
5 |
6 | public class Misspelling {
7 |
8 | public static void main(String[] args) {
9 |
10 | String content = "This is may calandar. This is june calander. This is may calendar.";
11 | String regex = "c[ae]l[ae]nd[ae]r";
12 | Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
13 | Matcher matcher = pattern.matcher(content);
14 |
15 | while (matcher.find()) {
16 | System.out.print("Start index: " + matcher.start());
17 | System.out.print(" End index: " + matcher.end() + " ");
18 | System.out.println(matcher.group());
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/regex/StartsWithEndsWith.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.regex;
2 |
3 | import java.util.List;
4 | import java.util.regex.*;
5 |
6 | public class StartsWithEndsWith {
7 |
8 | public static void main(String[] args) {
9 |
10 | List lines = List.of(
11 | "The cat is cute",
12 | "The category is empty",
13 | "The noncategory is also empty");
14 |
15 | Pattern pattern = Pattern.compile("\\bcat\\b", Pattern.CASE_INSENSITIVE);
16 |
17 | for(String line: lines) {
18 | Matcher matcher = pattern.matcher(line);
19 | while (matcher.find()) {
20 | //System.out.println(STR."Match found: \{matcher.group()}");
21 | }
22 | }
23 |
24 | pattern = Pattern.compile("\\b\\w*cat\\w*\\b");
25 |
26 | for(String line: lines) {
27 | Matcher matcher = pattern.matcher(line);
28 | while (matcher.find()) {
29 | System.out.println(STR."Match found: \{matcher.group()}");
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/xml/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/java/com/howtodoinjava/xml/README.md
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/xml/model/Department.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.xml.model;
2 |
3 | import jakarta.xml.bind.annotation.XmlAccessType;
4 | import jakarta.xml.bind.annotation.XmlAccessorType;
5 | import jakarta.xml.bind.annotation.XmlRootElement;
6 | import java.io.Serializable;
7 |
8 | @XmlRootElement(name = "department")
9 | @XmlAccessorType(XmlAccessType.FIELD)
10 | public class Department implements Serializable {
11 |
12 | private static final long serialVersionUID = 1L;
13 |
14 | Integer id;
15 | String name;
16 |
17 | public Department() {
18 | super();
19 | }
20 |
21 | public Department(Integer id, String name) {
22 | super();
23 | this.id = id;
24 | this.name = name;
25 | }
26 |
27 | public Integer getId() {
28 | return id;
29 | }
30 |
31 | public void setId(Integer id) {
32 | this.id = id;
33 | }
34 |
35 | public String getName() {
36 | return name;
37 | }
38 |
39 | public void setName(String name) {
40 | this.name = name;
41 | }
42 |
43 | //Setters and Getters
44 |
45 | @Override
46 | public String toString() {
47 | return "Department [id=" + id + ", name=" + name + "]";
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/xml/sax/SaxParserDemo.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.xml.sax;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.io.FileNotFoundException;
6 | import java.util.ArrayList;
7 |
8 | public class SaxParserDemo {
9 |
10 | public static void main(String[] args) throws FileNotFoundException {
11 | //Locate the file
12 | File xmlFile = new File("D:/temp/sample.xml");
13 |
14 | //Create the parser instance
15 | UserParser parser = new UserParser();
16 |
17 | //Parse the file
18 | ArrayList users = parser.parseXml(new FileInputStream(xmlFile));
19 |
20 | //Verify the result
21 | System.out.println(users);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/howtodoinjava/xml/sax/User.java:
--------------------------------------------------------------------------------
1 | package com.howtodoinjava.xml.sax;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | @Data
8 | @NoArgsConstructor
9 | @AllArgsConstructor
10 | public class User {
11 |
12 | private int id;
13 | private String firstName;
14 | private String lastName;
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/lambdaworks/jni/LibraryLoader.java:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2011 - Will Glozer. All rights reserved.
2 |
3 | package com.lambdaworks.jni;
4 |
5 | /**
6 | * A {@code LibraryLoader} attempts to load the appropriate native library
7 | * for the current platform.
8 | *
9 | * @author Will Glozer
10 | */
11 | public interface LibraryLoader {
12 | /**
13 | * Load a native library, and optionally verify any signatures.
14 | *
15 | * @param name Name of the library to load.
16 | * @param verify Verify signatures if signed.
17 | *
18 | * @return true if the library was successfully loaded.
19 | */
20 | boolean load(String name, boolean verify);
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/lambdaworks/jni/NilLibraryLoader.java:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2013 - Will Glozer. All rights reserved.
2 |
3 | package com.lambdaworks.jni;
4 |
5 | /**
6 | * A native library loader that refuses to load libraries.
7 | *
8 | * @author Will Glozer
9 | */
10 | public class NilLibraryLoader implements LibraryLoader {
11 | /**
12 | * Don't load a shared library.
13 | *
14 | * @param name Name of the library to load.
15 | * @param verify Ignored, no verification is done.
16 | *
17 | * @return false.
18 | */
19 | public boolean load(String name, boolean verify) {
20 | return false;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/lambdaworks/jni/SysLibraryLoader.java:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2011 - Will Glozer. All rights reserved.
2 |
3 | package com.lambdaworks.jni;
4 |
5 | /**
6 | * A native library loader that simply invokes {@link System#loadLibrary}. The shared
7 | * library path and filename are platform specific.
8 | *
9 | * @author Will Glozer
10 | */
11 | public class SysLibraryLoader implements LibraryLoader {
12 | /**
13 | * Load a shared library.
14 | *
15 | * @param name Name of the library to load.
16 | * @param verify Ignored, no verification is done.
17 | *
18 | * @return true if the library was successfully loaded.
19 | */
20 | public boolean load(String name, boolean verify) {
21 | boolean loaded;
22 |
23 | try {
24 | System.loadLibrary(name);
25 | loaded = true;
26 | } catch (Throwable e) {
27 | loaded = false;
28 | }
29 |
30 | return loaded;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/lambdaworks/jni/UnsupportedPlatformException.java:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2011 - Will Glozer. All rights reserved.
2 |
3 | package com.lambdaworks.jni;
4 |
5 | /**
6 | * Exception thrown when the current platform cannot be detected.
7 | *
8 | * @author Will Glozer
9 | */
10 | public class UnsupportedPlatformException extends RuntimeException {
11 | private static final long serialVersionUID = 1L;
12 |
13 | public UnsupportedPlatformException(String s) {
14 | super(s);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/resources/SampleCSVFile.csv:
--------------------------------------------------------------------------------
1 | 1,Lokesh,Gupta,howtodoinjava.com,enabled
2 | 2,Rakesh,Gupta,howtodoinjava.com,enabled
3 | 3,Manoj,Sharma,howtodoinjava.com,enabled
4 | 4,Abhay,Dwivedi,howtodoinjava.com,enabled
5 | 5,John,Adward,howtodoinjava.com,enabled
6 | 6,Steve,Jobs,howtodoinjava.com,disabled
7 | 7,Bill,Gates,howtodoinjava.com,enabled
8 | 8,Tom,Hanks,howtodoinjava.com,enabled
9 | 9,Dev,Patel,howtodoinjava.com,disabled
10 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #File Updated
2 | #Fri Aug 14 16:14:33 IST 2020
3 | firstName=Lokesh
4 | lastName=Gupta
5 | country=INDIA
6 | technology=java
7 | blog=howtodoinjava
8 |
--------------------------------------------------------------------------------
/src/main/resources/data.json:
--------------------------------------------------------------------------------
1 | [
2 | {"id":1,"name":"Alex","age":41},
3 | {"id":2,"name":"Brian","age":42},
4 | {"id":3,"name":"Charles","age":43}
5 | ]
--------------------------------------------------------------------------------
/src/main/resources/data/demo.txt:
--------------------------------------------------------------------------------
1 | Content from data/demo.txt
--------------------------------------------------------------------------------
/src/main/resources/dataOut.txt:
--------------------------------------------------------------------------------
1 | humpty dumpty sat on a wall
--------------------------------------------------------------------------------
/src/main/resources/demo.txt:
--------------------------------------------------------------------------------
1 | Content from demo.txt
--------------------------------------------------------------------------------
/src/main/resources/threaddumps/Fast_thread_report-Threaddumps.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lokeshgupta1981/Core-Java/68022f4b18e383456aa5d910e992c1108397010e/src/main/resources/threaddumps/Fast_thread_report-Threaddumps.pdf
--------------------------------------------------------------------------------