Showing posts with label Java 8 Features. Show all posts
Showing posts with label Java 8 Features. Show all posts

Tuesday, July 9, 2019

Sort Employees by Name and Age Using Java 8

This program for writing a program to sort the employee by name and age using JDK 8. Java 8 introduced many out of box features for developers. The comparator in java 8 is marked as @FunctionalInterface, and it provide a cleaner way to develop your code. We had already discussed how the Comparator<T> interface works before java 8. In this post, we will use the stream API with comparator. 


Employee.java


package com.techbyteslearn.lab.basic;

public class Employee {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
super();
this.name = name;
this.age = age;
this.department = department;
}
@Override
public String toString() {
return "\n Employee [name=" + name + ", age=" + age + ", department=" + department + "]";
}
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;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}


Now we will create an action or main method to use the above POJO class for sorting.

SortEmployeeWithStream.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Collectors;
public class SortEmployeeWithStream {
public static void main(String[] args) {
Employee1 e1 = new Employee1("Ander Koli", 32, "Sales");
Employee1 e2 = new Employee1("Andrew Smith", 23, "Sales");
Employee1 e3 = new Employee1("David Jone", 52, "Sales");
Employee1 e4 = new Employee1("Cuba Station", 23, "Marketing");
Employee1 e5 = new Employee1("Bradley Head", 23, "Marketing");
Employee1 e6 = new Employee1("Peter Parker", 34, "Sales");
// Create an arraylist and add all the employee object into that list.
ArrayList<Employee1> employeeList = new ArrayList<Employee1>();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
employeeList.add(e5);
employeeList.add(e6);
System.out.println("Employee list before sorting -\n" + employeeList);
ArrayList<Employee1> sortedList = (ArrayList) employeeList.stream()
.sorted(Comparator.comparing(Employee1::getName).thenComparing(Employee1::getAge))
.collect(Collectors.toList());
System.out.println("Employee list after sorting -\n" + sortedList);
}
}


Output-

Employee list before sorting -
[
 Employee1 [name=Ander Koli, age=32, department=Sales],
 Employee1 [name=Andrew Smith, age=23, department=Sales],
 Employee1 [name=David Jone, age=52, department=Sales],
 Employee1 [name=Cuba Station, age=23, department=Marketing],
 Employee1 [name=Bradley Head, age=23, department=Marketing],
 Employee1 [name=Peter Parker, age=34, department=Sales]]
Employee list after sorting -
[
 Employee1 [name=Ander Koli, age=32, department=Sales],
 Employee1 [name=Andrew Smith, age=23, department=Sales],
 Employee1 [name=Bradley Head, age=23, department=Marketing],
 Employee1 [name=Cuba Station, age=23, department=Marketing],
 Employee1 [name=David Jone, age=52, department=Sales],
 Employee1 [name=Peter Parker, age=34, department=Sales]]

The Comparator.comparing  and thenComparing  two static methods inside Comparator. As we know Comparator is a Functional interface which provides default and static methods along with implementation.  These functional interfaces are giving out of box functionality. See how before java 8 with Comparator interface examples.

Also we can achieve the above sorting by creating multiple different comparators , which we can use when we need. 

We have created two comparator as compareByAge, CompareByDept . Now we can use those comparators at any place we need along with stream. Below sample code snippet shows the usages. Read these reference documents for more about  stream, comparator, functions, jdk 8 features.


Comparator<Employee1> compareByAge = Comparator.comparing(Employee1::getAge);
Comparator<Employee1> compareByDept = Comparator.comparing(Employee1::getDepartment);
ArrayList<Employee1> sortedList = (ArrayList) employeeList.stream()
.sorted(compareByAge.thenComparing(compareByDept)).collect(Collectors.toList());


Sunday, April 22, 2018

Check NullPointerException in JDK 8 – Use Optional



How to handle NullPointerException or null check in JDK8 ? Checking null in JDK8 using Optional<T>.

NullPointerException is most common exception which each developer need to handle. Its very common while you are playing around many object. Before JDK 8 , it was a tedious task and lots of boilerplate code you need to write to handle this NullPointerException. But, after JDK 8 it Make your code more readable and protect it against null pointer exceptions. This API will help to write cleaner and more readable code , with intelligence to handle null check internally.

Below Example has few demonstration , how to use the Optional<T> api to avoid NullPointerException. You can handle Null check for your object.


Employee.java


package com.techbyteslearn.tutorial.jdk8;

public class Employee {
private String empName;
private int age;
private Address empAddress;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}

Address.java
package com.techbyteslearn.tutorial.jdk8;
public class Address {
private String homeUnitNo;
private String streetNo;
private String city;
public String getHomeUnitNo() {
return homeUnitNo;
}
public void setHomeUnitNo(String homeUnitNo) {
this.homeUnitNo = homeUnitNo;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

NullPointerCheck.java

package com.techbyteslearn.tutorial.jdk8; import java.util.Optional; public class NullPointerCheck { public static void main(String[] args) { String empName = null; /** * Before JDK 8, this will print "Print null". */ if (null != empName) { System.out.println("Print not null"); } else { System.out.println("Print null"); } /** * Before JDK 8, this throws NullPointerException. */ try { if (empName.equals("SomeThing")) { System.out.println("Print SomeThing"); } } catch (Exception e) { e.printStackTrace(); } /** * JDK 8 provides an easy and clean API, i.e. Optional<T>, * for handling this type of scenario. */ Optional<String> optionalString = Optional.ofNullable(empName); if (optionalString.isPresent()) { System.out.println("Employee Name ::" + empName); } /** * How to work with your own objects. */ Employee employee = new Employee(); employee.setEmpName("Peter"); Optional<Employee> optionalEmployee = Optional.ofNullable(employee); if (optionalEmployee.map(Employee::getEmpAddress).isPresent()) { System.out.println(employee.getEmpName() + "- Address is registered"); } else { System.out.println(employee.getEmpName() + "- Address is null"); } Employee employee1 = new Employee(); employee1.setEmpName("Mark Garret"); Address address = new Address(); address.setCity("Sydney"); employee1.setEmpAddress(address); Optional<Employee> optionalEmployeeWithAddress = Optional.ofNullable(employee1); if (optionalEmployeeWithAddress.map(Employee::getEmpAddress).isPresent()) { System.out.println( employee1.getEmpName() + "- Address is " + address.getCity()); } else { System.out.println(employee1.getEmpName() + "- Address is null"); } /** * Use Optional.empty() to represent an empty value. */ Employee empObject = new Employee(); System.out.println( "Returns Optional empty Value ::" + Optional.empty()); /* * Optional.of() does not handle null values. Be careful when using * this method. Use ofNullable() when the value may be null. */ System.out.println( "Returns Optional empty Value ::" + Optional.of(empObject) .map(Employee::getEmpAddress) .isPresent()); } }

Output:

Print null java.lang.NullPointerException at com.javadevelopersguide.tutorial.jdk8.NullPointerCheck.main(NullPointerCheck.java:48) Peter- Address is null Mark Garret- Address is Sydney Returns Optional empty Value ::Optional.empty Returns Optional empty Value ::false

 

Small technical note: Optional.of(empObject) itself is safe here because empObject is not null. The map() operation then produces Optional.empty() because getEmpAddress() returns null.

I have used below methods from Optional<T> :-

empty() - Returns an empty Optional instance


of() - Returns an Optional with the specified present non-null value.


isPresent() - If a value is present, invoke the specified consumer with the value, otherwise do nothing.


map() - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.


ofNullable() - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.


There are few more methods are there, you can give a try. Below link will give you a complete information. Read more about the Optional<T> by JDK 8.



Hope it will help you.