Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Showing posts with label JAVA 8 FEATURES. Show all posts
Showing posts with label JAVA 8 FEATURES. Show all posts

Sunday, December 10, 2017

Method Reference Example in Java 8

Java 8 New Feature with Method Reference

Java 8 Method Reference Example

In the previous article, We learned some new java 8 features with examples e.g lambda expressions in java 8, functional interface in java 8, default and static method in java 8, etc. but here we are going to see important and basic method reference example in java 8 tutorial.

Java 8 method reference is used to refer method of functional interface and to make program or code simple or clear you can use method reference instead of lambda expression.

It is shorthand notation of lambda expression to call any method.

'::' operator is used for method reference in java programs.

Before starting java 8 method reference example, let's see some types of method references one-by-one.


Types of Method Reference 

There are some java referece types of method reference which is given below with syntax.

1) Reference to an instance method 

syntax:

object :: instanceMethod

2) Reference to a static method

syntax:

Class :: staticMethod

3) Reference to an instance method of an arbitrary object of a particular type.

syntax:

Class :: instanceMethod

4) Reference to a constructor

syntax:

Class :: new


Let's understand above all the given java reference types with simple examples one-by-one.



(1) Reference to an instance Method

In this java 8 method reference example, We will create functional interface first and then a simple class with instance method and then we will use our method referece concept to refere to an instance method of an object.

@FunctionalInterface
interface Demo
{
void show();
}

public class Test
{
public void display()
{
System.out.println("I am instance method");
}
public static void main(String args[])
{
Test t = new Test();
Demo d = t :: display;//performing method reference using object
d.show();//calling method of function interface
}
}

Output: I am instance method


(2) Reference to a static method

interface Demo1
{
void show();
}

class Test1
{
public static void display()
{
System.out.println("Hi, i am static method of a class");
}
public static void main(String args[])
{
Demo1 dd = Test1 :: display;//perfroming method reference using class name
dd.show();
}
}

Output: Hi, i am static method of a class

Let' take another java method reference example


(3) Reference to an instance method of an arbitrary object of a particular type

This is another example of method reference to an instance method of an arbitray object of a particular type.

import java.util.Arrays;
class Test
{
public static void main(String args[])
{
String str[] = {"pink", "orange", "black", "red"};
Arrays.sort(str, String :: compareToIgnoreCase);

for(String str1 : str)
{
System.out.println(str1);
}
}
}

Output: black
             orange
             pink
             red


(4) Reference to a constructor

interface Demo4
{
FullName show(String s);
}

class FullName
{
FullName(String s)
{
System.out.println(s);
}
}

class Test
{
public static void main(String args[])
{
Demo4 d = FullName :: new;//performing constructor reference
d.show("Anurag Singh");
}
}

Output: Anurag Singh

In this java 8 tutorial, we saw 4 types of method references and some java 8 method reference examples step-by-step. I hope this java 8 new feature post will be helpful to you.

Share:

Wednesday, November 22, 2017

What is Functional Interface in Java 8

Functional Interface in Java 8

Java 8 Functional Interfaces

In this java 8 tutorial, We are going to learn new feature of java 8 which is functional interface.

There are so many new features are introduced in java 8 e.g default and static method, new date and time API, Lambda Expressions etc. functional interface is one of them.

Let's start with the definition of functional interface.


What is Functional Interface in Java 8?

Functional interface is a interface which contains only one abstract method. We can call functional interface as Single Abstract Method Interface(SAM).

We can declare any number of default and static methods in java functional interface. 

We can also declare methods of Object class in Functional Interfaces.

By using functional interfaces in java 8 we can achieve functional programming. 

There are many predefined Functional Interfaces in java 8 which is provided by java and we can create own functional interface in java.

Functional interface provides target type for lambda expressions and method references.


Predefined Functional Interfaces in Java 8

There are many predefined functional interfaces in java which are available in java.util.function package. Some of them are given below...

1) BiConsumer<T, U>

It represents an operations that accepts two input arguments and returns no result.

2) BiFunction<T, U, R>

It represents a function that accepts two arguments and produce a result.

3) BinaryOperator<T>

It represents an operation upon two operands of the same type, producing a result of the same type as the operands.

4) BiPredicate<T, U>

It represents a predicate(boolean - value function) of two arguments.

5) BooleanSupplier

It represents supplier of boolean-valued result.

6) Consumer<T>

It represents an operations that accepts a single input argument and returns no result.

7) DoubleBinaryOperator

It represents an operations upon two double valued operands and producing double valued results.

8) DoubleFunction<R> 

It represents a function that accepts a double valued arguments and produces result.

9) ToDoubleBiFunction<T, U>

It represents a function that accepts two arguments and produces a double valued result.

10) ToIntBiFunction<T, U>

It represents a function that accepts two arguments and produces an int valued result.

Let's take a look some examples of Functional Interface.


Java 8 Functional Interface Example

This is simple functional interface example in java 8 new feature.

@FunctionalInterface//It is optional
interface Dog
{
void run(String s);//Single abstract method
}

class Test implements Dog
{
public void run(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
Test t =
new Test();
t.run("run fast");
}
}

Output: run fast


Predefined Functional Interface Example

This is simple example of predefined functional interface and here we will use lambda expressions.

import java.util.function.IntBinaryOperator;
class PredefinedExample
{
public static void main(String args[])
{
//using  java 8 lambda expressions
IntBinaryOperator add = (x, y) -> x + y;
System.out.println(add.applyAsInt(9, 91));
}
}

Output: 100


Object Class Method in Functional Interface

We can declare only one abstract method in functional interface. We can also declare Object class method in Functional Interface.

@FunctionalInterface
interface Dog
{
void run(String s);//abstract method
String toString();//method of Object class
boolean equals(Obj o);//method of Object class
}


In this functional interface tutorial of java 8, we have learned what is a functional interface in java with simple examples e.g with lambda expressions and without lambda expressions.

Share:

Wednesday, November 15, 2017

How to get Current Date and Time with Java 8 New Features

Current Date and Time in Java 8

Current Date and Time in java 8 Features

In this article, We are going to learn how to get current data and time by using java 8 new features with simple examples step-by-step.

Here we will use some new java 8 date time API to display the data and time in java.

Here we are going to use some java 8 date and time classes which are given below.

  • java.time.LocalDate class
  • java.time.LocalTime class
  • java.time.LocalDateTime class
We can also use some old classes to get the current data and time in java e.g Date and Calendar classes but here we will focus only above listed 3 classes which is java 8 LocalDate, LocalTime, and LocalDateTime.

Let's start with LocalDate class.


Java 8 LocalDate Class

Java 8 LocalDate class are defined in java.time.* package and it contains several useful methods but here we are using now() method which is a static method.

LocalDate class represents date in this format year-month-day

Java 8 LocalDate class is a final class i.e it is immutable class and LocalDate class extends Object class and implements several interfaces like Serializable, ChronoLocalDate, Temporal, TemporalAdjuster.


LocalDate Class Example 

This is simple LocalDate class example for printing date.

class DateExample
{
public static void main(String args[])
{
//display the current date from the system clock in the default time zone
System.out.println("Current date is : "+java.time.LocalDate.now());
}
}

Output: Current date is : 2017-11-16


Java 8 LocalTime Class

Java 8 LocalTime class is defined in java.time.* package and it contains several useful methods but here we are going to use LocalTime.now() method which is static method.

LocalTime class represents time in this format hour-minute-second.

Time is represented to nanosecond precision.

Java 8 LocalTime class is also a immutable class i.e it is final class and it extends Object class and implement several interface like Serializable, Comparable<LocalTime>, etc.

LocalTime Class Example

This is simple LocalTime class example for printing time in java.

class TimeExample
{
public static void main(String args[])
{
//display the current time form the system clock in the default time-zone
System.out.println("Current time is : "+java.time.LocalTime.now());
}
}

Output: Current time is : 13:9:59.546


Java 8 LocalDateTime Class

Java 8 LocalDateTime class is also defined in java.time.* package and it also contains some useful method but here we will use LocalDateTime.now() method for representing date and time in java.

LocalDateTime class represents date and time both int this format year-month-day-hour-minute-second.

LocalDateTime class is final class i.e it immutable class and this class extends Object class and implement interfaces like Serializable, Temporal, TemporalAdjuster, etc.

LocalDateTime Class Example

This is simple example LocalDateTime class where will display both date and time together.

class DateTimeExample
{
public static void main(String args[])
{
//display the date and time from the system clock in default time-zone
System.out.println("Current date-time is : "+java.time.LocatDateTime.now());
}
}

Output: Current date-time is : 2017-11-16T13:27:10.087

here we learned how to get current date and time by using some new java 8 API like LocalDate class, LocalTime class and LocalDateTime class. There are other new classes in java 8 date and time api but we will learn in later.

Share:

Thursday, November 9, 2017

Java 8 Lambda Expressions Tutorial with Examples

Java 8 Lambda Expressions Tutorial

Java 8 lambda Expression Tutorial

In this article, We are going to cover java 8 lambda expressions tutorial with examples one-by-one in a simple way. Lambda expression is a new feature which introduced in java 8 programming language.


What is Lambda Expression?

There are many new features introduced in java 8 e.g default and static method in an interface, Array parallel sorting, StringJoiner class, etc. and Lambda expression is one of them which is introduced in java 8 version.

Java 8 lambda expression is used to provide the implementation of the functional interface, An interface which has only one abstract method known as a functional interface.

Lambda expression is anonymous function i.e function with no name. This function does not belong to any class.

Lambda expression concept was first introduced in LISP programming language and the in other programming languages like C,C++,Ruby,Scala,.Net, C#, Java, etc.

Lambda expression is also useful for iterate and extracts the data from the collection.


Advantages of Lambda Expression

There are many advantages of lambda expressions and these are given below.
  • To enable functional programming in java.
  • Lambda expression reduces the length of the code.
  • By using lambda expression we write more readable and maintainable code in java.
  • To enable parallel processing.


Syntax of Lambda Expression

(parameter_list) -> {body}

It contains three parts:

Parameter List: Parameter list may be empty or non-empty.

Arrow operator: This is lambda operator which connect the parameter list and body expression.

Body: It contains expression and statements for lambda expressions.

Java Lambda Expression Example

In this example, we will provide the implementation of function interface by using the lambda expression.

For example:

@FunctionalInterface
interface LambdaExample
{
public void eat();
}
class Test 
{
public static void main(String args[])
{
LambdaExample l = () -> {

System.out.println("eat rice");

};
l.eat();
}
}

Output: eat rice


Java Lambda Expression Example with No Parameter

This is the first java 8 anonymous function example i.e lambda expression example with no parameter.

For example:

@FunctionalInterface
interface MyFunctional
{
public String run();//without parameter
}
class First 
{
public static void main(String args[])
{
MyFunctional mf = () -> {

return "fast";
};

System.out.println(mf.run());
}
}

Output: fast

@FunctionInterface is used to declare an interface as the functional interface in java. It is optional.


Java Lambda Expression Example with One Parameter

This single parameter example of java 8 lambda expression.

For example:

interface My
{
public String watch(String s);
}
class Second 
{
public static void main(String args[])
{
My m = (watching) -> {

return "enjoying "+watching;
};
System.out.println(m.watch("cricket"));
}
}

Output: enjoying cricket


Java Lambda Expression Example with multiple parameters

In this lambda expression example, we will pass two parameters.

For example:

interface My
{
public String hello(String a, String b, String c);
}
class Third 
{
public static void main(String args[])
{
My m = (a, b, c) -> a+b+c;
System.out.println(m.hello("I", "am", "good"));
}
}

Output: I am good


Java Lambda Expression Example with Collection

This is the example of lambda expression with collection and foreach loop.

For example:

import java.util.*;
class LambdaWithCollection
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("red");
list.add("black");
list.add("pink");
list.add("white");
list.add("orange");

list.forEach((n) -> System.out.println(n));
}
}

Output: red
             black
             pink
             white
             orange

Read More:

Method Reference Example in Java 8.
What is Functional Interface in Java 8.
Java 8 Date and Time Programs.
Java Enum with Examples.
Java Reflection Tutorial with Examples.
Top 10 Java Programming Interview Questions.


Here we have discussed java 8 lambda expression with simple and easy examples.

Share:

Friday, October 20, 2017

Java 8 StringJoiner class with Examples

Java StringJoiner Class Examples

Java StringJoiner- java 8

Java 8 introduced some new features e.g default and static method and lambda expression, parallel array sort, method reference, etc. But here we are going to learn in detail which is java 8 StringJoiner class.


Java StringJoiner

StringJoiner is a new feature of java 8 technology and this class is belongs to the java.util package.

Java StringJoiner is public final class and extend Object class in java.

Syntax: public final StringJoiner extends Object

StringJoiner class is used to construct a sequence of characters separated by delimiters i.e you can create string by using some delimiters like ","(comma) and "-"(hyphen), etc. We can also use prefix and suffix for character sequence.


Java StringJoiner Constructor

There are two constructor of StringJoiner class provided by java.

  1. StringJoiner(CharSequence delimiter). 
  2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix). 

Java StringJoiner Methods

There are some StringJoiner methods which we will use in string joiner examples.
  • StringJoiner add(CharSequence newElement).
  • int length().
  • StringJoiner merge(StringJoiner other).
  • StringJoiner setEmptyValue(CharSequence emptyValue).
  • String toString().

Java StringJoiner Example by using delimiters

This is the first example of StringJoiner where we use delimiter for adding some strings and using add() method of StringJoiner class.

import java.util.*;
class Demo
{
public static void main(String args[])
{
StringJoiner sj = new StringJoiner(",");//passing comma (,) as delimiter
StringJoiner sj1 = new StringJoiner("-");//passing hyphen (-) as delimiter

//Adding some string with comma(,) delimiter
sj.add("suresh");
sj.add("gurpreet");
sj.add("piyush");
sj.add("jagdish");

System.out.println(sj);
System.out.println();

//Adding some string with hyphen(-) delimiter
sj1.add("simran");
sj1.add("siya");
sj1.add("khusboo");
sj1.add("barkha");

System.out.println(sj1);
}
}

Output: suresh,gurpreet,piyush,jagdish

             simran-siya-khusboo-barkha


Java StringJoiner Example by using prefix and suffix

import java.util.StringJoiner;
class Demo1
{
public static void main(String args[])
{
//passing , as delimiter and using "(" opening bracket as prefix and ")" closing bracket as suffix.
StringJoiner sj = new StringJoiner(",","(",")");

sj.add("blue");
sj.add("red");
sj.add("pink");
sj.add("white");

System.out.println(sj);
}
}

Output: (blue,red,pink,white)


Java StringJoiner Example: Merge two StringJoiner

In this example, We will take 2 StringJoiner and then use merge() method of StringJoiner class for merging or adding 2 StringJoiner.

import java.util.*;
class Demo3
{
public static void main(String args[])
{
//Creating first StringJoiner with delimiter and prefix and suffix
StringJoiner sj1 = new StringJoiner(",","*","*");
sj1.add("rose");
sj1.add("lotus");

System.out.println(sj1);

//Creating second StringJoiner with delimiter and prefix and suffix
StringJoiner sj2 = new StringJoiner(":","*","*");
sj2.add("red");
sj2.add("pink");

System.out.println(sj2);

//Now using merge() method for merging sj1 and sj2 joiners
StringJoiner mrg = sj1.merge(sj2);
System.out.println(mrg);
}
}

Output: *rose,lotus*
              *red:pink*
              *rose,lous,red:pink*


Java StringJoiner Methods Example

Here we will use some methods of StringJoiner class.

import java.util.*;
class Demo4
{
public static void main(String args[])
{
StringJoiner sj1 = new StringJoiner(",");

/* if StringJoiner is empty then we can print a massage for this StringJoiner by using setEmptyValue(). */

sj1.setEmptyValue("This is empty StringJoiner");
System.out.println(sj1);
System.out.println("add some values");

//now adding some string by using add() method
sj1.add("c++");
sj1.add("html");

System.out.println("added values is: "+sj1);

//After adding values, let's count the length of string by using length() method

int length = sj1.length();
System.out.println("Length of SJ "+length);
}
}

Output: This is empty StringJoiner
              add some values
              added values is: c++,html
              Length of SJ 8



I hope, this java 8 StringJoiner class example article will be useful to you.

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Blog Archive

Translate