Posts

Showing posts with the label Java8

Default Methods in Interface - Java 8

Java interfaces use to have only abstract methods thanks to JDK 8 which allows the interface to add default and static methods. During the application enhancement or maintenance, it may possible that new methods are required to be added in an interface that forced all implemented classes to be changed and implement new abstract methods. Thus we can add these default methods to existing interfaces without breaking the code and changing old implementation classes. interface DefaultMethod {  public default void defMethod(){    System.out.println("Default Method");  } } public class TestDefault implements DefaultMethod{   public static void main(String[] args) {     TestDefault t = new TestDefault();      t.defMethod();    } } Likewise, you can define  default static methods  in an interface with the restriction of not overriding static methods.

Java Streams API - Process set of elements

Image
A Stream is a series of objects. Source of a stream is an Array, Collection, or Other I/O source. A Stream does not store data, it does only intermediate operations. It can filter and manipulate the elements of its source. Streams are lazy, the source and intermediate operations do nothing until objects are needed by the terminal operation. Steams APIs are contained by java.util.stream package.  A water filter is the best example of streams.   It processes the water stream.  It has multiple filters that work one after another.  Filters do purification, reverse osmosis, refinement of water, and produce drinking water.  The water filter does not store the water it simply processes the water stream. Getting Started  1. Create a Stream and print all elements  Let's create a stream from a collection and print all its elements.  The following example creates a Stream from the list collection and prints all elements of the collection using its forEa...