In this post, we will see about Java 8 tutorial.
I have written a lot of tutorials on Java 8. This is index post for all Java 8 posts.
Table of Contents
Lambda expression
Lambda expression is a representation of anonymous function which can be passed around. Lambda expression does not have name but it has parameters, body and return type.
Basic syntax of lambda expression is like below:
or
(parameters) -> { statements; }
As you can see if you have multiple statements then you need to put curly braces.
Functional interface
The functional interface is the interface which can have only one abstract method.
Functional interface and lambda expression go hand in hand. You can write lambda expression for function interface.
For example:
Runnable interface
1 2 3 4 5 |
public interface Runnable { public abstract void run(); } |
Default methods in interface
Java 8 has introduced a lot of new methods in interfaces but it might break older version code. If any class does not implement interface’s method then it gives compilation error. To tackle this issue, Java 8 has the introduction of default methods. It might sound surprising but interface can have implementation code as well. You can declare default method in the interface and it won’t force client to implement default method.
For example:
reversed() is default method in Comparator interface.
Static methods in interface
Similar to default methods, you can have static method too in the interface.
For example:
naturalOrder() is static method in Comparator interface.
Optional
Java 8 Optional can be used to avoid NullPointerException.I have written detailed Java 8 optional tutorial.
Stream API
Stream is one of the biggest addition to Java 8. Stream API help you to process data in declarative manner similar to SQL queries.
For example:
Let’s say you want to filter employees of age greater than 30 and create a list of names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog; public class Employee { private String name; private int age; public Employee(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
Create a class "EmployeeMain" which will use both conventional and java 8’s stream to filer list of employees.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class EmployeeMain { public static void main(String[] args) { List<Employee> employeeList = createEmployeeList(); List<String> filterEmployeeByAge = filterEmployeeByAge(employeeList); System.out.println("Filtered list of employees using conventional way:"); for (String employeeName:filterEmployeeByAge) { System.out.println(employeeName); } System.out.println("================================"); System.out.println("Filtered list of employees using Stream : "); List<String> filterEmployeeByAgeWithStream = filterEmployeeByAgeWithStream(employeeList); for (String employeeName:filterEmployeeByAgeWithStream) { System.out.println(employeeName); } } public static List<String> filterEmployeeByAge(List<Employee> employeeList) { // Using conventional way List<String> employeeFilteredList=new ArrayList<>(); for(Employee e:employeeList) { if(e.getAge()>20) { employeeFilteredList.add(e.getName()); } } return employeeFilteredList; } public static List<String> filterEmployeeByAgeWithStream(List<Employee> employeeList) { // Using Java 8 Stream List<String> employeeFilteredList = employeeList.stream() .filter(e->e.getAge()>20) .map(Employee::getName) .collect(Collectors.toList()); return employeeFilteredList; } public static List<Employee> createEmployeeList() { List<Employee> employeeList=new ArrayList<>(); Employee e1=new Employee("John",21); Employee e2=new Employee("Martin",19); Employee e3=new Employee("Mary",31); Employee e4=new Employee("Stephan",18); Employee e5=new Employee("Gary",26); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); return employeeList; } } |
When you run above program, you will get below output
John
Mary
Gary
================================
Filtered list of employees using Stream :
John
Mary
Gary
As you can see, Stream can help you write code in consite and clean way.
Java 8 Date/Time
Java 8 has introduced new Date and time APIs. It is buillt to cover all the flaws of Date and Calendar APIs which we have been using for so long.
Let’s see some of new API classes.
LocalDate
LocalDate class represents Date only. There is no time or timezone information.
1 2 3 4 5 6 |
LocalDate localDate=LocalDate.now(); System.out.println("Year: "+localDate.getYear()); System.out.println("Month: "+localDate.getMonth()); System.out.println("Day:"+localDate.getDayOfMonth()); |
Output:
Month: MAY
Day:20
LocalTime
LocalDate class represents Time only. There is no Date or timezone information.
1 2 3 4 5 6 |
LocalDate localDate=LocalDate.now(); System.out.println("Year: "+localDate.getYear()); System.out.println("Month: "+localDate.getMonth()); System.out.println("Day:"+localDate.getDayOfMonth()); |
Output:
Minute: 32
Second:54
LocalDateTime
LocalDateTime class represents date and time both. There is no timezone information.
1 2 3 4 5 6 7 8 9 |
LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("Year: "+localDateTime.getYear()); System.out.println("Month: "+localDateTime.getMonth()); System.out.println("Day:"+localDateTime.getDayOfMonth()); System.out.println("Hour: "+localDateTime.getHour()); System.out.println("Minute: "+localDateTime.getMinute()); System.out.println("Second:"+localDateTime.getSecond()); |
Output:
Month: MAY
Day:20
Hour: 0
Minute: 35
Second:40
Instant
Instant class is used to represent time stamp in java.You can perform plus, minus and various other operations on Instant.
1 2 3 4 5 6 |
Instant instance1 = Instant.now(); Instant instance2=instance1.plusSeconds(5); System.out.println("Instant 1: "+ instance1); System.out.println("Instant 2: "+ instance2); |
Output:
Instant 2: 2018-05-19T19:10:28.540064Z
Duration
Duration class represents time interval between two instants in second or milliseconds.
1 2 3 4 5 6 7 |
Instant start = Instant.parse("2018-10-13T11:15:35.00Z"); Instant end = Instant.parse("2018-10-13T11:16:35.00Z"); Duration duration = Duration.between(start, end); System.out.println("Duration in seconds: "+duration.getSeconds()); |
Output:
That’s all about Java 8 tutorial.
Nice post, easy to read and understand.
I have only one comment about fixing the link of Interface static methods in java 8.
many thanks