Tuesday, January 19, 2021

Java 8 Quick Recap

1.) What is Optional? Why and how can you use it?

Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.
Optional class encapsulates optional value which is either present or not.
It is a wrapper around object and can be use to avoid NullPointerExceptions.
Let’s take a simple example. 
You have written below function to get first non repeated character in String.

You call above method as below.

Do you see the problem, there is no non repeating character for getNonRepeatedCharacter("SASAS") hence it will return null and we are calling c.toString(), so it will obviously throw NullPointerException.
You can use Optional to avoid this NullPointerException.
Let’s change the method to return Optional object rather than String.

When above method returned Optional, you are already aware that it can return null value too.
You can call Optional’s isPresent method to check if there is any value wrapped in Optional.

If there is no value present in Optional, it will simply print "No non repeated character found in String".

2.) Given the list of employee, group them by employee name?

You can use Collections.groupBy() to group list of employees by employee name.

Output:

Name: John ==>[Employee Name: John age: 21, Employee Name: John age: 26] Name: Martin ==>[Employee Name: Martin age: 19] Name: Mary ==>[Employee Name: Mary age: 31, Employee Name: Mary age: 18]

3.) Difference between Intermediate and terminal operations in Stream?

Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns elements that are satisfying the supplied condition by the predicate.

map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by applying the supplied mapper function.= sorted() - Sorts the input elements and then passes them to the next stage.

distinct() - Only pass on elements to the next stage, not passed yet.

limit(long maxsize) - Limit the stream size to maxsize.

skip(long start) - Skip the initial elements till the start.

peek(Consumer) - Apply a consumer without modification to the stream.

flatMap(mapper) - Transform each element to a stream of its constituent elements and flatten all the streams into a single stream.

most common type of Terminal operations?

  • collect() - Collects single result from all elements of the stream sequence.
  • reduce() - Produces a single result from all elements of the stream sequence
    • count() - Returns the number of elements on the stream.
    • min() - Returns the min element from the stream.
    • max() - Returns the max element from the stream.
  • Search/Query operations
    • anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
    • Takes a Predicate as input for the match condition.
    • Stream processing will be stopped, as and when the result can be determined.
  • Iterative operations
    • forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
    • forEachOrdered() - It is helpful to maintain order in parallel streams.
4.) Why do we need default methods in java

This is for backwards compatibility.

If you have an interface that other people have implemented then if you add a new method to the interface all existing implementations are broken.

By adding a new method with a default implementation you remaining source-compatible with existing implementations.

For a slightly simple/contrived example that should hopefully demonstrate this let us say you created a library:

void drawSomething(Thing thing) {
}

interface Thing {
    Color getColor();
    Image getBackgroundImage();
}

Now you come to do a new version of your library and you want to add the concept of border colors, that's easy to add to the interface:

interface Thing {
    Color getColor();
    Color getBorderColor();
    Image getBackgroundImage();
}

But the problem is that every single person using your library has to go back through every single Skin implementation they ever did and add this new method.

If instead you provided a default implementation to getBorderColor that just called getColor then everything "just works".

1 comment:

  1. As a leading Top Mobile App Development Company, Appsinvo company is well known to design and build customized web and mobile app solutions for the clients. Complete integration of the mobile app and the website gives the businesses a boost not only in their growth but also in the revenue.
    Full Stack Developers in Delhi
    Top Mobile App Development Company in Qatar
    Top Mobile App Development Company in kuwait

    ReplyDelete

Top DataStructures Problem from Medium-2

  Array: Find a pair with the given sum in an array Maximum Sum Subarray Problem (Kadane’s Algorithm) Longest Increasing Subsequence Problem...