preloader

Java 8 is functional programming based version of java which focus on decreasing length
of program make application expression based using new property

Java8

  • COURSES

    03 Month

  • DURATION

    01 Hours

New features of Java 8?

Following are new introduces features of java8
  • Functional interface
  • Lembda expression
  • Optional classes
  • Date and Time Api
  • Stream Api
  • String Joiner
  • Method referencing

Functional interface

Functional interface is single abstract method interface having only one abstract value but multiple default and static method.
it use lembda expression for implimentation which reduce the length of code and create expression based structure.

@FunctionalInterface annotation is used in order to strict follow but it is not necessary for application
Some predefined functional interface are present before only are –
Runnable, ActionListener, Comparable .
Newly introduced functional interfaces are –
predicate ,consumer and supplier, function

Difference between Predicate and function

Predicate function
it takes 2 parameters one input type argument and other return type it take only one value of input type argument
it can return any type value it returns Boolean output
it has abstract method apply() it has abstract method test()
it is used for implementation of condition check it is used for transformation and return value

Difference between Static and Default

Static method Default method
Static method can invoke only on interface class not on class. It can be invoked on interface as well as class
Interface and implementing class , both can have static method with
the same name without overriding each other
We can override the default method in implementing class
It can be used as a utility method It can be used to provide common
functionality in all implementing classes
public interface Test{
static void display() {
System.out.println(“In static method “);
}
}
public interface Test{
default void show() {
System.out.println(“In default method")
}
}

what is Optional Class in java?

Optional classes are public final classes that is used to deal with null pointer exception in java8

import java.util.Optional;
                public class OptionalClasses {
                    public static void main(String[] args) {
                        String[] str = new String[10];
                        Optional op = Optional.ofNullable(str[5]);
                        if (op.isPresent()) {
                            String st = str[5].toString();
                            System.out.println(st);
                        } else {
                            System.out.println(“No string”);
                        }
                    }
                }

Define Date and time API

  • Date and time api in java 8 is synchronized and thread safe .
  • Previous version we need to pass java.util and java.sql required for its use but in java 8
    we have java.time package itself for this feature.
  • Timezone feature was added in java 8 which help time details according to time zones
  • Localdate, Localtime,Localdateandtime api are added along with now () method for system date and time
  • Faster performance in comparison to old version.
For current date we can use it
            LocalDate d = localDate.now();
            System.out.println(dt);
For current date and time we can use it
                Localdateandtime dt = Localdateandtime.now();
                System.out.println(dt);
For current date and time we can use it
                    Localtime t = Localtime.now();
                    System.out.println(t);

Different function of Date and Time api

import java.time.LocalDate;
            import java.time.LocalDateTime;
            import java.time.LocalTime;
            import java.time.ZoneId;
            import java.time.ZonedDateTime;
            import java.util.Set;
            
            
            public class DateANdTime {
                public static void main(String[] args) {
                    LocalDate date = LocalDate.now();
                    System.out.println(date);
                    LocalTime time = LocalTime.now();
                    System.out.println(time);
                    LocalDateTime current = LocalDateTime.now();
                    System.out.println(current);
                    ZonedDateTime xx = ZonedDateTime.now();
                    System.out.println(xx);
                    Set < String > zone = ZoneId.getAvailableZoneIds();
                    System.out.println(zone + " \n");
                    ZonedDateTime xxc = ZonedDateTime.now(ZoneId.of("America/New_York"));
                    System.out.println(xxc);
                }
            }

Steam Api

Stream represents a sequence of objects from a source such as a collection,
which supports aggregate operations.
They were designed to make collection processing simple and concise

Difference between Intermediate and Terminal

Intermediate Terminal
Intermediate operations return a stream Terminal operations return non-stream values
like primitive or object or collection
Chained together to form a pipeline of operations Terminal operations can not be chained together
Lezy by nature Execute as soon as created
They don’t produce end result. They produce end result.
  • map()
  • filter()
  • distinct()
  • sorted()
  • limit()
  • skip()
  • forEach()
  • toArray()
  • reduce()
  • collect()
  • min()
  • max()
  • count()
  • anyMatch()
  • allMatch()
  • noneMatch()
  • findFirst()
  • findAny()

Difference between map vs Flatmap

Map Flatmap
processes stream
of values.
processes stream
of stream of values.
It does only mapping. It performs mapping
as well
as flattening.
used for finite value of data. used for infinite value of data.
It’s mapper function
produces single value
for each input value.
It’s mapper function
produces multiple values
for each input value.
It is a
One-To-One mapping.
It is a
One-To-Many mapping
Data Transformation
: From Stream to Stream
Data Transformation
: From Stream of Stream
to Stream
List (String)
namesOfInstitutes
= instituteList.stream()
.map(Institute::
getName).collect
(Collectors .toList());
Set(String)
locationsOfInstitutes
= instituteList.stream()
.flatMap(institute ->
institute.getLocations()
.stream()). collect
(Collectors.toSet());

Difference between Collection and Steam

Collection Stream
Part of JDK 1.2 Part of JDK 1.8
Used to store different type of object in a single entity. Streams are mainly used to perform operations on data.
used for finite value of data. used for infinite value of data.
add or remove elements from collections can’t add or remove elements from streams
Collections can be traversed multiple times Streams are traversable only once.
Collections are eagerly constructed. Streams are lazily constructed.
Example :-List, Set, Map Example : –filtering, mapping

Difference between Iterator vs Splitor

Iterator Splitor
iterator is part of JDK 1.2 splitor is part of JDK1.8
iterator part of collection Api Splitor is part of steam Api
Only Sequential order Both Parallel and Sequential order
it is pure Iterator it is unpure Iterator

StringJoiner in Java8

Joining the strings or concatenating the strings is the frequent
operation while programming any kind of applications.

  • java.util.StringJoiner class
  • String.join() method
  • Collectors.joining() method
StringJoiner Example : Joining the strings with delimiter
import java.util.StringJoiner;
 
            public class Java8StringJoiner 
            {
                public static void main(String[] args) 
                {
                    StringJoiner stringJoiner = new StringJoiner(" | ");
                     
                    stringJoiner.add("Facebook");
                     
                    stringJoiner.add("Twitter");
                     
                    stringJoiner.add("YouTube");
                     
                    stringJoiner.add("WhatsApp");
                     
                    stringJoiner.add("LinkedIn");
                     
                    System.out.println(stringJoiner);
                }
            }
            Output :
            
            Facebook | Twitter | YouTube | WhatsApp | LinkedIn
StringJoiner Example : Joining the strings with delimiter, prefix and suffix
import java.util.StringJoiner;
 
                public class Java8StringJoiner 
                {
                    public static void main(String[] args) 
                    {
                        StringJoiner stringJoiner = new StringJoiner(", ", "[", "]");
                         
                        stringJoiner.add("Facebook");
                         
                        stringJoiner.add("Twitter");
                         
                        stringJoiner.add("YouTube");
                         
                        stringJoiner.add("WhatsApp");
                         
                        stringJoiner.add("LinkedIn");
                         
                        System.out.println(stringJoiner);
                    }
                }
                
                Output :
                
                [Facebook, Twitter, YouTube, WhatsApp, LinkedIn]
String.join() Method Example : Joining the strings
public class Java8StringJoinMethod 
                    {
                        public static void main(String[] args) 
                        {
                            String joinedString = String.join(" | ", "Facebook", "Twitter", "YouTube", "WhatsApp", "LinkedIn");
                             
                            System.out.println(joinedString);
                        }
                    }
                    
                    Output :
                    
                    Facebook | Twitter | YouTube | WhatsApp | LinkedIn
String.join() Method Example : Joining an array of strings
public class Java8StringJoinMethod 
                        {
                            public static void main(String[] args) 
                            {
                                String[] strArray = new String[] {"Facebook", "Twitter", "YouTube", "WhatsApp", "LinkedIn"};
                                 
                                String joinedString = String.join(" | ", strArray);
                                 
                                System.out.println(joinedString);
                            }
                        }
                        
                        Output :
                        
                        Facebook | Twitter | YouTube | WhatsApp | LinkedIn
String.join() Method Example : Joining list of strings
import java.util.Arrays;
                            import java.util.List;
                             
                            public class Java8StringJoinMethod 
                            {
                                public static void main(String[] args) 
                                {
                                    List<String> listOfStrings = Arrays.asList("Facebook", "Twitter", "YouTube", "WhatsApp", "LinkedIn");
                                     
                                    String joinedString = String.join(" | ", listOfStrings);
                                     
                                    System.out.println(joinedString);
                                }
                            }
                            
                            output:
                            Facebook | Twitter | YouTube | WhatsApp | LinkedIn

What is Method Reference

Method reference used to refer to the method of functional interface.
It can be used to replace Lambda Expression while referring to a method.

Lembda Expression Equivalent Method Reference
(String s)->integer.parseInt integer::parseInt
(String s)->s.toLowerCase String::toLowerCase
(int i)->System.out.println(i) System.out::println
(Student s)->s.getName(); Student::getName
()->s.getName() s::getName
()->new Student() Student::name
import java.util.function.Function;

                public class Java8MethodReferences {
                    public static void main(String[] args) {
                        //Calling parseInt() method using lambda
                
                        Function < String, Integer > lambdaFunction = (String s) - > Integer.parseInt(s);
                        System.out.println(lambdaFunction.apply("12"));
                
                        //Calling parseInt() method using method reference
                
                        Function < String, Integer > referenceFunction = Integer::parseInt;
                        System.out.println(referenceFunction.apply("12"));
                    }
                }

Related Course

course thumb

Basic Java

All basic level question for java covered in this section

Visit
course thumb

OOP Concept

Inheritance,Polimorphism,Abstraction and Encapsulation

Visit
course thumb

Core Java

Core java, OOP concept, Multithreading, Collection and Exception Handling

Visit