Posts

Showing posts with the label Java 8

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 BinaryOperator Example

In this blog post, I will be explaining how the Java 8 BinaryOperator functional interface works. To know more about functional interfaces, you can refer to  this  blog post. Edit What is BinaryOperator The BinaryOperator is a specialization of the BiFunction interface that accepts 2 arguments. However, unlike the BiFunction it accepts 2 arguments of the same data type and returns a result of the same data type. The BinaryOperator internally uses the BiFunction.apply method. BinaryOperator Interface Example with Integer data type Consider the following code snippet: BinaryOperator<Integer> additionCalculator = (a, b) -> a +b;int input1 = 6;int input2 = 5;System.out.println("Result of adding " + input1 + " and " + input2 + " is " + additionCalculator.apply(input1, input2));   Here, we have written a BinaryOperator implementation that operates on Integer data type. It accepts two integer values, adds them and returns the result. The BiFu...

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...

Stream API Filter examples with code samples

In this blog post, I will be demonstrating the filter method provided by Java 8 Stream API.In order to understand the Stream API in detail, refer to  this  blog post. Edit Introduction The filter method in the Stream API can be applied on an existing Stream. It creates a new Stream with all the elements that match the condition specified in the filter method. It accepts a Predicate instance which is an in-built functional interface. Refer  this  blog post for a detailed  Predicate  example. Code Sample with Integer public class FilterStreamDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); Stream<Integer> stream = input.stream().filter(num -> num >= 9); stream.forEach(num -> System.out.println(num)); }} This code uses the filter method to obtain all the elements that are greater than 9 .  It first obtains a stream instance on the input ArrayList using the  stream() method. Then the...

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...

How to find the number of days between two Dates

In this post, I am going to demonstrate how you can find the number of days between two dates. The following code snippet demonstrates this:   Code snippet </pre>public static void main(String[] args) {try {DateFormat df = new SimpleDateFormat("yyyy-MM-dd");Date today = df.parse("2018-08-24");Date future = df.parse("2018-09-04");// Date future = getFutureDate();int daysBetween = daysBetween(today,future);System.out.println("days between = "+daysBetween);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static int daysBetween(Date date1, Date date2){long time1 = date1.getTime(); //Returns no of milliseconds since January 1, 1970, 00:00:00 GMTlong time2 = date2.getTime();long diffInMs = time2-time1;int numOfMsInOneDay = 1000 * 60 * 60 * 24;int daysBetween = (int) (diffInMs / numOfMsInOneDay);return daysBetween;}<pre>   Explanation The Date.getTime method is first used for each Date obj...