Showing posts with label java8. Show all posts
Showing posts with label java8. Show all posts

Tuesday, 14 October 2025

How to use BiFunction functional interface in java 8 ?

BiFunction is a Functional interface with only one abstract method apply(T t, U u), which takes two arguments and return a result of type R. It is a generic interface defined as BiFunction<T, U, R>

BiFunction interfaces are typically implemented as lambda expressions.

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {
public static void main(String[] args) {
BiFunction<String, String, String> biFunction = (s1, s2) -> s1 + s2;
System.out.println(checkStr(biFunction));
Function<String, String> function = r -> "Result : " + r;
System.out.println(biFunction.andThen(function).apply("b", "c"));
}

private static Boolean checkStr(BiFunction<String, String, String> biFunction) {
if ("ab".equals(biFunction.apply("a", "b"))) {
return true;
}
return false;
}
}

Result:

true

Result : bc

Monday, 13 October 2025

How to use Duration class in java.time ?

Duration class in java.time package was introduced in Java 8 new Date and Time API.

It represents a time-based amount of time such as `34.5seconds`, `2 hours`. It deals with quantity of time with seconds and nanoseconds precision as well. In addition, DAYS unit can be used and it is treated like 24 hours amount of time, without considering any daylight saving effects. For date based amounts of time one can use java.time.Period class.

Duration class is immutable class and thread-safe. Duration class has static factory methods ofDays(), ofHours(), ofMinutes(), ofSeconds(), ofMillis(), and ofNanos() like for Duration instance creation.
import java.time.Duration;
import java.time.LocalDateTime;

public class DurationExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = LocalDateTime.of(2025, 10, 13, 22, 52, 0);
System.out.println("Current date time: " + now);
//30 minutes amount of time
Duration duration = Duration.between(now, then);
System.out.println("Duration between now and then " + duration);

//add 10 hours and 2 minutes for the duration
Duration changedDuration = duration.plusHours(10).plusMinutes(2);
System.out.println("changed duration : " + changedDuration);

Duration lessDuration = Duration.ofSeconds(30);
//convert duration to nanoseconds and millis
System.out.println("less duration in nanos : " + lessDuration.toNanos());
System.out.println("less duration in millis : " + lessDuration.toMillis());
}
}

Result:

Current date time: 2025-10-13T21:55:26.190489700
Duration between now and then PT56M33.8095103S
changed duration : PT10H58M33.8095103S

Sunday, 14 November 2021

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.

Monday, 22 December 2014

STATIC METHODS & DEFAULT METHODS IN AN INTERFACE - JAVA 8 EXICITING FEATURES

Static Methods in interfaces

Prior to Java 8, we have many utility classes with static methods which are commonly used.

For Example, for Collection interface, we have utility class Collections


likewise,

path - Paths

Executor - Executors

So, To reduce the utility classes, java designers introduced static methods
in interfaces.

Note:

. A static method contains a static modifier.

. They are implicitly public.

. Have implementation logic within the interface.

 
Example:
public interface Blog {
int followers_count = 0;
void comment();
//A static convenience method
public static void subscribe(){
//implementation logic
System.out.println("you have successfully subscribed");
}
}

DEFAULT METHODS in an interface 

From Java 8,  you can also declare DEFAULT methods in interface.


DEFAULT METHODS is new feature added in Java 8.


To understand the concept of default methods and its purpose, lets consider that
I have designed a library which is having the above declared interface Blog.

Lets take an assumption that, those who want to make blog must implement my interface Blog.

So I have distributed the interface to all the interested people who want to blog.

 Now, the many of my bloggers are satisfied with the methods available in the 
interface.

But, If one of the bloggers wants to add his/her own methods to the interface, like say adding a new method share().

So They would have to request me to add the method share() method and again I would distribute the library to all the bloggers.

Now, If the bloggers try to use the this new library - the old code breaks because 
share() method must be implemented by all the bloggers.

In java 8, this problem is alleviated by introducing DEFAULT methods in the interface.

default methods have a default modifier and an implementation logic in the interface itself.

So, If I make share() as a default method in the interface - old code breaking problem will be solved.

Thanks to Default methods.

Note:

. Must have a default modifier

. have an implementation logic within the interface.


Example:


public interface Blog {
int followers_count = 0;
void comment();

//A static convenience method
public static void subscribe(){
System.out.println("you have successfully subscribed");
}

default String share(){
System.out.println("You have shared your blog");
return "Success";
}
}



 Hope this is helpful.                                                     
   
 If you like this, please share.