Nitin Agrawal
Contact -
  • Home
  • Interviews
    • Secret Receipe
    • InterviewFacts
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • Companies
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems >
        • Problem10
        • Problem300
      • AnagramsSet
    • Core Java >
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Java Releases >
        • Java8 >
          • Performance
          • NasHorn
          • WordCount
          • Thoughts
        • Java9 >
          • ServiceLoaders
          • Lambdas
          • List Of Objects
          • Code Snippets
        • Java14 >
          • Teeing
          • Pattern
          • Semaphores
        • Java17 >
          • Switches
          • FunctionalStreams
          • Predicate
          • Consumer_Supplier
          • Collectors in Java
        • Java21 >
          • Un-named Class
          • Virtual Threads
          • Structured Concurrency
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • Sample Code Part 1 >
        • PatternLength
        • Serialization >
          • Kryo2
          • JAXB/XSD
          • XStream
        • MongoDB
        • Strings >
          • Reverse the String
          • Reverse the String in n/2 complexity
          • StringEditor
          • Reversing String
          • String Puzzle
          • Knuth Morris Pratt
          • Unique characters
          • Top N most occurring characters
          • Longest Common Subsequence
          • Longest Common Substring
        • New methods in Collections
        • MethodReferences
        • Complex Objects Comparator >
          • Performance
        • NIO >
          • NIO 2nd Sample
        • Date Converter
        • Minimum cost path
        • Find File
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • TemplatePattern
        • Adapter Design Pattern
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • Singleton >
          • Singletons
        • Strategy
  • Frameworks
    • Apache Velocity
    • React Library >
      • Tutorial
    • Spring >
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • Custom Beans
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Messaging Formats
      • Design Patterns
    • AWS >
      • Honeycode
    • Dockers >
      • GitBash
      • Issues
      • Kubernetes
  • Databases
    • MySql
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search
  • Random issues
    • TOAD issue
    • Architect's suggestions
  • Your Views
Will be trying to share one or the other things with small code snippets here, which one can use to understand some features or concepts.
Note :- Below code snippets might have been created using either Java9 or Java11, so please try to switch the jdk if anyone of the below doesn't work on your system, as all the below snippets are working for me.
Picture
Just have a look at the above code, its simple, right?
But I found it useful to know about the features around Optional in Java.
Try below cases to understand the differences -
1) Comment Line# 3 & uncomment Line# 2 only, leave Line# 1 commented.
     Execute the code. Getting 'NoSuchElementException' ? Because it is the expected hazardous behaviour of get() in
     Optional which is why you can use safely only when you know that your Optional has value. As any get() is expected to
     return the value, if present, else don't do anything or can tell this nicely that no value is present but Exception? Who can
     expect this from any innocent get()?
 But we don't do this everytime, so what to do? Try option (2) below -
2) Uncomment Line# 1 also but keep Line# 3 commented here. Now you see the difference & can see the expected result with
     no exception. But this way we need to keep in mind to use the filter. Can we avoid this? So try (3) below -
3) Leave Line# 1 & Line# 2 commented & uncomment Line# 3
    Now check the output. You can still see the correct result with no exception but no filter is required. flatMap() does
    flattening of all the non empty Optional & put them in a stream, so after flatMap() you have a stream of 'Employee' objects.

Another case, suppose you want to return some default employee object if Optional is empty. As here it is not taking any action like you saw in case(2) & (3) above, though case(1) is throwing the exception but you don't want an exception either, you just want to have some default Employee object if Optional is empty.
And in this case you don't need case(2) & (3), implementation of case(1) will suffice you requirement as get() of Optional will never be empty. So what to do? Just replace the else part with below line -
                         opt = Optional.ofNullable(new Employee("Default"));
Now execute the code again like you did for case(1).
Check the below code for Comparator usage in functional way -
Picture
Picture
Picture
Check the below code snippet to see the usage of the predicates in filter which can be provided on the fly, to filter the list on custom conditions & this way we can implement the strategy pattern in our code.
Picture
Working on Dates has always been troubling & everytime we need to refer the internet when coding to handle dates. Below is one sample using old & new API & check www.java2s.com/Tutorials/Java/Java_Date_Time/0150__Java_Custom_Date_Format_Patterns.htm
to get various applicable format options.
Picture
Ever wondered about the old Fibonacci problem? How did you write it earlier?
You can remember those few lines of looping & swapping the values to generate the next fibonacci number & then putting the limit on how many such numbers you need.
Lets do the same in new Java like shown below & see its done in 3 lines -
Picture
Powered by Create your own unique website with customizable templates.