Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

10 July, 2019

Find one missing number from a list of numbers

In this article, we will find the missing number from a list of numbers using java 8.  This is one of important questions asked in interview. This program is to find the only one missing number. Check how to find all missing numbers from a list. In this program we will use only java 8 stream to find the missing number. Earlier post we had seen how to use stream to sort the employee. Check more how find one missing number using traditional core java style


FindMissingNumber.java

package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
/**
 * This program finds the missing number from a list. This is only for one
 * missing number. Used the java 8 for this program.
 *
 * @author manoj.bardhan
 *
 */
public class FindMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 4, 5, 6, 7, 9, 10));
// Get the Max value from the List.
int maxValue = numberList.stream().max(Comparator.naturalOrder()).get().intValue();
// Get sum of all natural numbers - upto the above maxvalue
int sumOfAllNumber = IntStream.range(1, maxValue + 1).sum();
// Get the sum of all number inside List.
int sumofList = numberList.stream().mapToInt(Integer::intValue).sum();
// Now print the missing number.
System.out.println("The Missing Number is:: " + (sumOfAllNumber - sumofList));
}
}



Output - 

The Missing Number is:: 8




Happy Learning.



Follow for more details on @Facebook!!!

Find More  :-

08 July, 2019

Java Comparator Example for custom sorting by employee age and department

This program illustrates , how to sort custom object using Comparator<T>. We have used Employee list to sort by age and department. As per the default ordering it will follow the natural ordering.

The below Employee class is our POJO , we will use this class to sort the employee list by age and department.

Employee.java

package com.javadevelopersguide.lab.basic;
/**
 * @author manoj.bardhan
 *
 */
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 need to create a comparator to compare two same objects. We can create as many comparators by implementing each field/attributes of the POJO. Its purely business requirement, how you need your sorting functionality. Here we need the sorting based on the employee  age and employee department.

EmployeeAgeComparator.java

package com.javadevelopersguide.lab.basic;
import java.util.Comparator;
/**
 * EmployeeAgeComparator is a comparator by Age.
 *
 * @author manoj.bardhan
 *
 */
public class EmployeeAgeComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}


EmployeeDeptComparator.java

package com.javadevelopersguide.lab.basic;
import java.util.Comparator;
/**
 * EmployeeDeptComparator is comparator by department.
 *
 * @author manoj.bardhan
 *
 */
public class EmployeeDeptComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
// Internally for comparing String we need to use compareTo()
return emp1.getDepartment().compareTo(emp2.getDepartment());
}
}

In the above we created two comparator for age and department. Now, we need to action on our comparators. We will call our newly created comparator from main() and see the result. Below EmployeeComparatorExample class show the comparator in action.


EmployeeComparatorExample.java

package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Collections;
/**
 * This program illustrates the simple use of Comparator<t> interface.
 *
 * @author manoj.bardhan
 *
 */
public class EmployeeComparatorExample {
public static void main(String[] args) {
Employee e1 = new Employee("Matt Kuban", 32, "IT");
Employee e2 = new Employee("Andrew Smith", 42, "HR");
Employee e3 = new Employee("Butler Jason", 52, "HR");
Employee e4 = new Employee("Miss Linda", 35, "HR");
Employee e5 = new Employee("Bradley Head", 23, "IT");
Employee e6 = new Employee("Peter Parker", 34, "ADMIN");
// Create an arraylist and add all the employee object into that list.
ArrayList<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
employeeList.add(e5);
employeeList.add(e6);
System.out.println("Employee Before Sort ::" + employeeList);
// Using EmployeeAgeComparator - to sort the employee by Age
EmployeeAgeComparator ageComparator = new EmployeeAgeComparator();
Collections.sort(employeeList, ageComparator);
// Using EmployeeDeptComparator - to sort the employee by Department
EmployeeDeptComparator deptComparator = new EmployeeDeptComparator();
Collections.sort(employeeList, deptComparator);
System.out.println("Employee After Sort ::" + employeeList);
}
}

Output :- 

Employee Before Sort ::[
 Employee [name=Matt Kuban, age=32, department=IT],
 Employee [name=Andrew Smith, age=42, department=HR],
 Employee [name=Butler Jason, age=52, department=HR],
 Employee [name=Miss Linda, age=35, department=HR],
 Employee [name=Bradley Head, age=23, department=IT],
 Employee [name=Peter Parker, age=34, department=ADMIN]]

Employee After Sort ::[
 Employee [name=Peter Parker, age=34, department=ADMIN],
 Employee [name=Miss Linda, age=35, department=HR],
 Employee [name=Andrew Smith, age=42, department=HR],
 Employee [name=Butler Jason, age=52, department=HR],
 Employee [name=Bradley Head, age=23, department=IT],
 Employee [name=Matt Kuban, age=32, department=IT]]

Happy Learning.



21 April, 2018

Check NullPointerException in jdk 8 - Use Optional



How to handle NullPointerException or null check in jdk 8 ? Checking null in jdk 8 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.javadevelopersguide.tutorial.jdk8;
/**
 * Employee Object
 *
 * @author manoj.bardhan
 *
 */
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.javadevelopersguide.tutorial.jdk8;
/**
 * Address Object
 *
 * @author manoj.bardhan
 *
 */
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.javadevelopersguide.tutorial.jdk8;
import java.util.Optional;
/**
 * This Example demonstrate how to use JDK 8 Optional<T> Api
 *
 * @author manoj.bardhan
 *
 */
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, throws NullPointerException
*/
try {
if (empName.equals("SomeThing")) {
System.out.println("Print SomeThing");
}
} catch (Exception e) {
e.printStackTrace();
}
/**
* So Now , jdk 8 provides 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() for set the default value for an object.
*/
Employee empObject = new Employee();
System.out.println("Returns Optional empty Value ::" + Optional.empty());
/*
* Optional.of() method doesn't handle NullPointer, be careful of this
* method while using.Always use the ofNullable() before null check.
*/
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



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.

25 January, 2017

Write your first Groovy Program

Write your first Groovy Program



If you remember we already discussed in my previous post about adding Groovy to your resume. Adding new skills will always help and increase your chance of getting your dream job.

Before everything you should have hands on experience on groovy programming. Lets see how to write a simple groovy program. As a newbie for groovy , you should start a basic hello world program.


Before start your first groovy program , you should make sure you have groovy installed in your machine (Desktop/Laptop). I am using Linux (ubuntu) here to demonstrate this example.

You can check in your terminals and I have already installed Groovy. Below command I have used to check whether groovy is installed and what version of groovy I am using.


root@jdg-HP-ProBook-6450b:~/grovytest$ type groovy
groovy is hashed (/usr/bin/groovy)
root@jdg-HP-ProBook-6450b:~/grovytest$ groovy -version
Groovy Version: 1.8.6 JVM: 1.7.0_121 Vendor: Oracle Corporation OS: Linux


Now, we can write our first groovy program. Usually groovy files are saved with extension xxx.groovy. Groovy program doesn't required semicolon (;) to close like java.This is very simple and reduce the developer effort of coding.


Open vi editor or text pad. Lets start writing your first program. 


Below is a Sample groovy program :-

HelloWorld.groovy



println "Say Hello to Groovy"


Now save this file with extension .groovy. In this example I have given the file name as HelloWorld.groovy.

Now you need to execute this .groovy file using below command  on terminal and check the output. 

root@jdg-HP-ProBook-6450b:~/grovytest$ groovy HelloWorld.groovy
Say Hello to Groovy

Now you can see the output I have highlighted in color. This is a simple groovy program. Find more programs on my subsequent posts.


Hope this will help you!!!





Follow for more details on Google+ and @Facebook!!!

Find More :-