Sunday, 14 November 2021

What is LocalDate in Java 8 ?

LocalDate class is an immutable & thread safe class. Its based on ISO-8601 calendar system.

It represents a date without any time components. Its date format often viewed in the form year-month-day {2021-11-14}.

Using this class, you can also access other data fields like :

    > day-of-year

    > day-of-week

    > week-of-year

Example:

public class LocalDateEx{

public static void main(String[] args) {
LocalDate date = LocalDate.of(2021, 4, 14);
System.out.println("Year of the given date "+ date.getYear());
System.out.println("Month of the given date "+ date.getMonth());
System.out.println("day of week of the given date "+ date.getDayOfWeek());
System.out.println("day of month of the given date "+ date.getDayOfMonth());
System.out.println("day of year of the given date "+ date.getDayOfYear());
System.out.println("day of year of the given date "+ date.getDayOfYear());
System.out.println("month of year(1 to 12) of the given date "+
                                                                                             date.getMonthValue());
        System.out.println("is given date a leap year? "+ date.isLeapYear());
System.out.println(date);
}
}


Factorial of any number in Java 8 - using reduction

Reduction - will reduce a stream of values to a result by using an identity (may be an initial value) and a function that will be applied internally on that stream. This processing may not be sequentially, its parallel stream.

import java.util.stream.LongStream;


public class Factorial {
public static void main(String[] args) {
    System.out.println(facto(5));
}

public static int facto(int n){
return IntStream.rangeClosed(1, n)
.reduce(1, (int a, int b) -> a * b);
}
}
we can either use LongStream or IntStream. 
LongStream.rangeClosed(1, n) gives stream of values from 1 to n, 
n is included here.
if you want to exclude nth value, 
you can use
LongStream.range(1, n) gives stream of values from 1 to n-1.
reduce function will apply a function a*b with 1 as initial value
 (also known as identity)
Its the similar operation as the following code.
long result = identity;
* for (long element : this stream)
* result = accumulator.applyAsLong(result, element)
* return result;
But the above code performs the same operation in sequential manner, 
but the reduce will apply the function in parallel form.