Posts

Showing posts with the label Java 8 New Features

Java 8 Optional Explained with code samples

Java 8 has introduced a bunch of new features. The Optional feature introduced by Java 8 helps in avoiding unexpected exceptions. In this article, I will be covering this feature in detail. Edit Optional Introduction An optional can be used to represent a value that can either be present or absent. Many times methods return a null value. If the code that invokes the method expects a non-null value, this can result in a NullPointerException . To avoid this, you need to add explicit null checks in your code. This can make the code difficult to read. Consider the following code: Person person = new Person();if(person != null){ // Null Check String name = person.getName();} The above code needs to have an explicit null check for Person object. Only if the person object is not null, the code invokes the getName method. Java 8 Optionals help to avoid explicit null checks like this. So you can re-write the above code using an Optional as follows: Optional<Person> person = Option...

Java 8 LocalDateTime class explained with code samples

Just like the LocalDate and LocalTime classes, Java 8 has also introduced the LocalDateTime class. In this article, I will be covering this class. Edit What is LocalDateTime class? The Java 8 LocalDateTime class represents a date with a time component. It has the year, month, day, hour, minute, second and nanoseconds components. So for example, you can use it to represent a date time like 12th August 1997 7:30 am . LocalDateTime Creation There are several static methods on the LocalDateTime class that can be used to create a LocalDateTime. The following code demonstrates this:   LocalDateTime dateTime1 = LocalDateTime.now();  System.out.println("Today's date is "+dateTime1);    LocalDateTime dateTime2 = LocalDateTime.parse("2019-07-15T10:15:30");  System.out.println("Date2 is "+dateTime2);    dateTime2 = LocalDateTime.of(2017,05,17,5,25);  System.out.println("Date3 is "+dateTime2);   The LocalDateTime.now returns the current time. Th...

Java 8 Map compute methods with code samples

In this article, I will be covering the Java 8 Map compute methods.Java 8 has introduced the Map.compute, Map.computeIfPresent example, and Map.computeIfAbsent methods. Edit compute The compute method computes a new value for a particular key and updates the Map with the new value. Even if the specified key is not present in the map, it computes the value for the key and adds the key-value mapping to the Map . The following code demonstrates this: Map <Integer,String> students = new HashMap<Integer,String>();students.put(100, "Swati Shashtri");students.put(101, "Gina George");students.put(102, "Puja Khanna"); students.compute(100, (key,value) -> value+",Pune");System.out.println(students.get(100));students.compute(101, (key,value) -> value+",Bangalore");System.out.println(students.get(101));   Here, there is a Map that has a student id as the key and student name as the value. There are 3 entries in the Map...

Java 8 SplitIterator Explained with code samples

Another new feature in Java 8 is the SplitIterator interface. This article will explain what a SplitIterator is and how you can use it. Edit What is a SplitIterator? Just like a normal Iterator, you can use a SplitIterator to iterate over the elements in a Collection. A new method called splitIterator has been added to all the Collection interfaces. This returns a SplitIterator instance. The following code demonstrates this: public class SplitIteratorDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 21, 15, 9, 2, 12, 11); Spliterator<Integer> sitr1 = input.spliterator(); sitr1.forEachRemaining(num -> System.out.println(num)); }} The above code obtains a SplitIterator over the input list. Just like the Iterator interface, the forEachRemaning method is also available on the SplitIterator interface. This can be used to iterate through the elements in the input collection. So when you execute the above code, it pri...

Java 8 Collection removeIf method with code samples

Java 8 has added a new method called removeIf to the Collection interface. You can use this to remove an element from a Collection in Java. In this article, I will be explaining the how this method works. Edit What does RemoveIf do? This method removes an element from the Collection that matches a particular condition. It returns a boolean value which indicates whether some values were removed or not.  The condition to be checked is specified via a Predicate instance. Predicate is an in-built functional interfac e that accepts an argument of any data type and returns a boolean.  You can implement it via a lambda expression . RemoveIf Integer Code Sample The following code demonstrates this method on an Integer List: public class RemoveIfDemo { public static void main(String[] args) { List<Integer> input = new ArrayList<Integer>(); input.add(5); input.add(12); input.add(17); input.add(18); input.add(25); boolean anyElementRemoved = input.remo...

Java 8 Iterator forEachRemaining method with code samples

Java 8 has added a method called forEachRemaning to the Iterator interface. This helps in using an Iterator to internally iterate over a Collection, without an explicit loop. In this article, I will be covering this method with a code sample. Edit Pre Java 8 code Before Java 8, you had to write code similar to the following in order to use an Iterator: public class ForEachRemainingDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); Iterator<Integer> itr = input.iterator(); while(itr.hasNext()) System.out.println(itr.next()); }} So in this code, you need to use a while loop in order to use the iterator to iterate through the input list. Using Java 8 forEachRemaining Java 8 added the forEachRemanining method to the Iterator interface. So using this method, the above code can be re-written as follows: public class ForEachRemainingDemo { public static void main(String[] args) { List<Intege...

Java 8 LocalTime class in with code samples

What is LocalTime class? The Java 8 LocalTime class represents a time. It has the hour, minute, second and nanoseconds components. So for example, you can use it to represent a time like 7:30. It does not have a date, year or month component. Edit LocalTime Creation There are several static methods on this class that can be used to create a LocalTime object. The following code demonstrates this: LocalTime time1 = LocalTime.now();System.out.println("Current time is "+time1);LocalTime time2 = LocalTime.parse("12:30");System.out.println("time2 is "+time2);LocalTime time3 = LocalTime.of(5, 30);System.out.println("time3 is "+time3);   The LocalTime.now returns the current time. The LocalTime.parse parses the specified time and creates a LocalTime object out of it. It requires the Time to be in hh-mm format. If you specify the time in some other format, an error will occur. If your String time is in any other format, you can use the overloaded ve...

Java 8 LocalDate Class explained with code samples

Another new feature by Java 8 is the DateTime API. Some of the important classes in the DateTime API are the LocalDate, LocalTime and LocalDateTime . In this article, I will be explaining the Java 8 LocalDate class in detail. Edit Introduction The LocalDate class represents a date. It is present in the java.time package. It has several methods that allow you to perform date manipulation easily. Creating LocalDate There are several static methods on the LocalDate class that allow you to obtain a LocalDate instance. The following code demonstrates this: public class LocalDateDemo { public static void main(String[] args) { LocalDate date1 = LocalDate.now(); System.out.println("Today's date is "+date1); LocalDate date2 = LocalDate.parse("2019-07-15"); System.out.println("Date2 is "+date2); LocalDate date3 = LocalDate.of(2017,05,17); System.out.println("Date3 is "+date3 ); LocalDate date4 = LocalDate.ofYear...

Java 8 Method Reference operator explained

Java 8 introduced an operator represented by a double colon(::), known as the “Method Reference” operator.   In this blog post, I will be explaining this operator. A basic understanding of lambda expessions is required in order to understand method references. Edit What is the Method Reference operator? The method reference operator can be used to refer to a method. Normally, you can implement a functional interface using a lambda expression. Sometimes, your code may already have a method that has the same functionality that you want your lambda expression to implement. So instead of re-writing the code using a lambda expression, you can implement the lambda expression via the existing method. Code Sample Consider the following code: @FunctionalInterfacepublic interface Shape { public void draw();} This is a functional interface called Shape. It has a single method called “draw()”. Now consider the following code for a class ShapeDrawingDemo public class ...

Lambda expressions in Java 8 explained with code samples

You Java 8 introduced a new feature called lambda expressions. In this blog post, I will be explaining lambda expressions in detail. Edit What are lambda expressions Lambda expressions are used to define anonymous functions, that is a function without a name.  Lambda expressions and functional interfaces together help in writing clean code. A functional interface is nothing but an interface with a single method. In order to understand more about functional interfaces, you can refer to this blog post. Lambda expressions can be used to implement functional interfaces. Lambda expression syntax The general syntax of a lambda expression is as follows: (parameters) -> {method body} Parameters Parameters specify the parameters to be passed to the lambda expression. You can pass one or more parameters. You need to enclose the parameters in parentheses. If there is only one parameter, you can skip the parentheses. Also, parameters are optional. If the lambda expression does not accept...

Java 8 Stream API explained with code samples

Java 8 introduced the Stream API. The Stream API along with lambda expressions can be used to perform bulk operations on the elements in a Collection. Not only that, you can pipeline the Stream operations to perform a number of sequential operations. Edit How do Streams work? A new method called stream has been added to all the Collection interfaces, this returns a  java.util.Stream interface. There are various methods on this stream interface that perform the corresponding operation on the Stream instance. Suppose you have an integer array. Suppose you want to find all the elements that are greater than the value 9. Before Streams and Java 8, you would need to write code like the following: public class FilterStreamDemo {public static void main(String[] args) {List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11);List<Integer> output = new ArrayList<Integer>();for(int num:input){if(num >= 9)output.add(num);}}} So this code iterates through the inpu...

Java 8 forEach loop explained with code samples

Java 8 introduced a lot of new features like functional interfaces, lambda expressions, etc. These provide a totally new way of programming for developers. One such feature is the forEach support added to the Collection interfaces. In this blog post, I will be covering this feature in detail. Edit What is forEach Java 8 added a new method called forEach to all the Collection interfaces via the Iterable interface. You can use this method to iterate through a Collection internally without the need for an explicit for loop. Before Java 8 Prior to Java 8, if we wanted to iterate through a Collection like a List , we had to write code similar to the following: public class ForEachDemo {public static void main(String args[]){List <Integer> list = Arrays.asList(5,3,11,15,9);for(int num:list){System.out.println("Number is "+num);}}} So you need to write a for loop to iterate through the elements in the List. In the body of the for loop, you can write the code that you wa...

Java 8 Functional Interface explained with code samples

Java 8 introduced the concept of functional interfaces. In this blog post, I will be explaining what a Java 8 functional interface is. Edit What is a functional interface? A functional interface is nothing but an interface that has only one abstract method. It can have more than one static and default methods, but it should have only one abstract method in order to qualify as a functional interface. Consider the following code snippet: package learnjava.java8;@FunctionalInterfacepublic interface MyFunctionalInterface {public void method1();public default void defaultMethod(){System.out.println("Default method");}public default void staticMethod(){System.out.println("Static method");}} Here, we have defined an interface called  MyFunctionalInterface . This has only one abstract method called method1 and so this is a functional interface. It also has a default and a static method. Note that we have specified the @FunctionalInterface annotation. This annotati...

Java 8 Static Interface methods with code samples

Just like default methods , Java 8 also supports static methods in interfaces. In this blog post, I will be explaining Java 8 static interface methods in detail. I will be covering what static methods are, how they work and why they were added. Edit What are static interface methods? Static interface methods are methods with the static keyword are with a method body. How do static interface methods work? Consider the following code snippet: </pre>public interface MyInterface {static public void staticMethod(){System.out.println("In staticMethod of interface");}}<pre> So in the code above, the staticMethod is a static interface method.  So we have defined a method with a method body within the interface. It has the static keyword specified. Prior to Java 8, the above code would have caused an error due to two reasons: There is a method with a method body within the interface There is a static method with in the interface How are they similar to default method...

Java 8 Default Interface methods explained

One of the new features provided by Java 8 is the support for default methods in interfaces. In this blog post, I will be explaining Java 8 default interface methods in detail. I will be covering what default methods are, how they work and why they were added. Edit What are default interface methods? Default methods are methods in an interface that have method bodies, They are specified with the  keyword “ default “. How do default interface methods work? Prior to Java 8, interfaces could not have method bodies.  So consider the following code snippet: public interface MyInterface {public void methodA();public void methodB(){System.out.println("In methodB");}}   This code causes a compilation error. This is because methodB has a method body.  However, if you are using Java 8, you can change the code as follows: public interface MyInterface {public void methodA();default public void methodB(){System.out.println("In methodB");}} So now, the def...