Showing posts with label Java Examples. Show all posts
Showing posts with label Java Examples. Show all posts

Monday, September 7, 2026

Why Are Interface Methods Public in Java?

Why Are Interface Methods Public in Java?

Do you know why methods in a Java interface are public?

Consider the following example:

interface IMyInterface {

    public void display();

    public void calculate();
}

// Implementation class
class MyImplClass implements IMyInterface {

    @Override
    public void display() {
        System.out.println("Hi: Override-Display");
    }

    @Override
    public void calculate() {
        System.out.println("Hi: Override-calculate");
    }

    // Class's own method
    public void show() {
        System.out.println("Hi: I am Own Method");
    }

    public static void main(String[] args) {

        IMyInterface f = new MyImplClass();

        f.display();
    }
}

Output

Hi: Override-Display

Why must an interface method be public?

An interface defines a contract that implementing classes agree to provide.

An abstract interface method is implicitly public, so the following declarations are equivalent:

interface IMyInterface { void display(); public void calculate(); }

Both methods are public abstract methods.

When a class implements an interface, it must provide an implementation that is at least as accessible as the interface method.

For example, this is valid:

class MyImplClass implements IMyInterface { public void display() { System.out.println("Display"); } }

But this is not valid:

class MyImplClass implements IMyInterface { private void display() { System.out.println("Display"); } }

The compiler will report an error because a private method has weaker access than the public interface method.

The same applies to protected:

protected void display() { // Invalid }

You cannot reduce the visibility of an interface method when implementing it.

Why is this important?

Consider:

IMyInterface obj = new MyImplClass(); obj.display();

The reference type is the interface. The interface promises that display() is publicly available.

Therefore, the implementation cannot suddenly make that method private or protected.

The interface establishes the public contract, while the implementing class provides the actual implementation.

An important modern Java point

The statement "all methods in an interface are public" is no longer completely accurate.

Since Java 8, interfaces can also contain default and static methods. Since Java 9, interfaces can contain private methods.

For example:

interface IMyInterface { void display(); // public abstract default void print() { System.out.println("Default method"); } static void info() { System.out.println("Static method"); } private void helper() { System.out.println("Private helper"); } }

So the more accurate statement is:

Abstract methods declared in an interface are implicitly public. Interface default and static methods are also public by default, while interfaces can additionally contain private methods for internal implementation.

Key point

An interface defines a contract between the interface and its implementing classes. An implementing class cannot provide a weaker access level for an interface method.

Understanding hashCode() in Java


Understanding hashCode() in Java

The hashCode() method is defined in the Object class and is used to return a hash code value for an object.

It is especially important when working with hash-based collections such as HashMap, HashSet, and Hashtable.

public int hashCode()


General contract of hashCode()

There are a few important rules that should be followed:

If hashCode() is called multiple times on the same object during a Java application execution, it should return the same integer value as long as the information used by equals() has not changed.

If two objects are considered equal according to the equals() method, they must return the same hash code. Two objects that are not equal do not have to return different hash codes. Different objects can have the same hash code. This is called a hash collision.

Having fewer collisions can improve the performance of hash-based collections.

Example

Consider the following class:

public class Employee {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Employee)) {
            return false;
        }

        Employee employee = (Employee) obj;

        return id == employee.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

Here, id is used to determine whether two Employee objects are equal. Therefore, the same id is also used to calculate the hash code.

This is important because:

Employee e1 = new Employee(101, "John");
Employee e2 = new Employee(101, "David");
System.out.println(e1.equals(e2)); // true 
System.out.println(e1.hashCode());
System.out.println(e2.hashCode());



Since both objects have the same id, they are considered equal and must have the same hash code.


Why is hashCode() important?

Hash-based collections use the hash code to efficiently locate objects.


For example:

HashSet<Employee> employees = new HashSet<>(); 

employees.add(new Employee(101, "John"));

employees.add(new Employee(101, "David"));

System.out.println(employees.size());


Because the two objects are considered equal based on id, the HashSet treats them as the same element.


Important point

  1. If you override equals(), you should also override hashCode().
  2. The basic rule to remember is:
  3. If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
  4. However, the reverse is not required:
  5. Same hash code does not mean that two objects are equal.

Find Number of Days Between Two Dates in Java

Find Number of Days Between Two Given Dates in Java

Sometimes we need to find the number of days between two given dates. Earlier, I used Calendar and manually calculated the difference between the dates.

With Java 8 and later, this can be done much more easily using the java.time package.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class FindDays {

    public static void main(String[] args) {

        String str1 = "20/01/2013";
        String str2 = "28/03/2013";

        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd/MM/yyyy");

        LocalDate date1 = LocalDate.parse(str1, formatter);
        LocalDate date2 = LocalDate.parse(str2, formatter);

        long days = ChronoUnit.DAYS.between(date1, date2);

        System.out.println("Final Days.... " + days);
    }
}

Output:

Final Days.... 67

How it works

DateTimeFormatter is used to tell Java the format of the input dates.

LocalDate represents a date without a time or timezone.

ChronoUnit.DAYS.between() calculates the number of days between the two dates.

For example:

20/01/2013 → 28/03/2013 = 67 days

The older Calendar approach can still be found in existing Java applications, but for new development, the java.time API is generally the better choice.


Understanding the super Keyword and Constructors in Java

Understanding the super Keyword and Constructors in Java

When talking about inheritance in Java, it is important to understand that constructors are not inherited by a subclass.

A subclass can, however, invoke a constructor of its super class using the super keyword.

A few points about the super keyword

  1. super is a Java keyword.

  2. It can be used to access members of the super class, such as fields and methods.

  3. It can be used to invoke a super class constructor.

  4. When calling a super class constructor using super(...), it must be the first statement in the subclass constructor.

Example

class SUP {

    public SUP(String s) {
        System.out.println("Hi Super: " + s);
    }
}

// SUB class extending SUP class
class SUB extends SUP {

    public SUB(String p) {

        // Explicitly call the super class constructor
        // super(...) must be the first statement
        super(p);

        System.out.println("Hi SUB: " + p);
    }

    public static void main(String[] args) {
        new SUB("Rahul Sharma");
    }
}

Output

Hi Super: Rahul Sharma
Hi SUB: Rahul Sharma

When the SUB object is created, its constructor first invokes the SUP constructor using super(p). After the super class constructor completes, the remaining statements in the SUB constructor are executed.

What happens if super() is not written?

If the super class has an accessible no-argument constructor, Java automatically inserts a call to super() as the first statement of the subclass constructor, provided you don't explicitly call another super class constructor.

For example:

class SUP {

    public SUP() {
        System.out.println("Hi Super");
    }
}

class SUB extends SUP {

    public SUB() {
        // Compiler automatically inserts super();
        System.out.println("Hi SUB");
    }
}

The output is:

Hi Super
Hi SUB

However, if the super class does not have an accessible no-argument constructor, the subclass must explicitly invoke one of the available super class constructors.

Important point

Constructors are not inherited in Java. They are invoked as part of object construction.

The super keyword allows a subclass to explicitly invoke a super class constructor and access super class members.

Saturday, September 5, 2026

JAVA: Implementing the Singleton Design Pattern for Creating a Single Instance with Example

Implementing the Singleton Design Pattern helps in creating only a single instance of a class. Below is a simple example for better understanding.

Class with Main Function

// Class with Main function for calling Singleton class public class TestSingleTon { public static void main(String[] args) { SingleTonClass classInstance = SingleTonClass.getInstance(); System.out.println( "My SingleTon member value is=" + classInstance.testval ); } }

Singleton Class

// Singleton class public class SingleTonClass { // Create an instance private static SingleTonClass my_instance = new SingleTonClass(); // Private constructor private SingleTonClass() { // Private Constructor here // Does not allow an object to be created outside this class } // Method to access the instance public static SingleTonClass getInstance() { return my_instance; } // Member variable int testval = 10; // If the comment is removed from the below line, // the program will not compile. // SingleTonClass s1 = new SingleTonClass(); }

Output

The output of this program is:

My SingleTon member value is=10

This is a simple implementation of the Singleton Design Pattern that ensures only one object is created.

There are also other ways to implement the Singleton Design Pattern, such as lazy initialization, thread-safe implementation, and handling Singleton instances across multiple JVMs.


Thursday, September 3, 2026

Find Duplicate Strings in a List Using Java | Java Interview Question

In this article, we will see how to find duplicate strings and their counts from an array or a list using Java. This is one of the common programming questions asked in technical interviews.

In this program, we will use both Map and List, so it is also a good example for understanding Java Collections. You can find a few more Java Collection interview questions.

Today, we will see how to find duplicate strings in a list and count how many times each string is repeated.

Logic

The logic is quite simple:

  • First, we create a Map to store the key-value pair. The key will be the array element, and the value will be the number of times that element occurs.

  • Then, we iterate through the array or list and add each element to the Map. If the element is already present in the Map, we increase its count by 1.

  • After completing the iteration, the Map will contain each string along with the number of times it occurs.

  • Finally, we iterate through the Map and check for entries where the count is greater than 1. These are the duplicate or repeated strings.


CountDuplicate.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(
Arrays.asList("JDG", "AA", "AA", "JAVA", "JavaScript", "Java", "Stream", "hibernate", "Hibernate"));
System.out.println("Input List = " + list);
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.isEmpty()) {
map.put(list.get(i).toUpperCase(), 1);
} else if (map.containsKey(list.get(i).toUpperCase())) {
map.put(list.get(i).toUpperCase(), map.get(list.get(i).toUpperCase()) + 1);
} else {
map.put(list.get(i).toUpperCase(), 1);
}
}
int counter = 0;
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
counter++;
System.out.println("String Found " + entry.getKey() + " with count " + entry.getValue());
}
}
System.out.println("Total Duplicate String - " + counter);
}
}



Output

Input List = [JDG, AA, AA, JAVA, JavaScript, Java, Stream, hibernate, Hibernate]

String Found: AA with count 2
String Found: JAVA with count 2
String Found: HIBERNATE with count 2

Total Duplicate Strings: 3

 

Happy Learning!



Saturday, July 13, 2019

Find Palindrome Strings in an Array Using Java


In this article, we will see how to find all palindrome strings from an array. This is a very frequently asked questions in interview.  Also there is a question to find all palindrome number from an array.  Find few more collection interview question.  

PalindromeStrings.java

package com.techbyteslearn.lab.basic;

/**
 * This program illustrates how to find palindrome strings from an array.
 */
public class PalindromeStrings {

    public static void main(String[] args) {
        String[] stringArray = {
            "eye",
            "jdg",
            "javadevelopersguide",
            "aabaa",
            "hello",
            "pip"
        };

        for (int i = 0; i < stringArray.length; i++) {
            printOnlyPalindrome(stringArray[i]);
        }
    }

    private static void printOnlyPalindrome(String str) {
        String oldString = str;
        StringBuilder builder = new StringBuilder(str);

        if (builder.reverse().toString().equals(oldString)) {
            System.out.println(oldString + " is a Palindrome String.");
        }
    }
}

Output:

eye is a Palindrome String.
aabaa is a Palindrome String.
pip is a Palindrome String.
Happy Learning.

Find All Palindrome Numbers from an Array in Java

In this article, we will see how to find all palindrome from an array. This is a very basic questions in interview, the interviewer will ask the same questions in different way. So, its good to know all possible questions from palindrome. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 

FindAllPalindrome.java

package com.techbyteslearn.lab.basic;

public class FindAllPalindrome {
public static void main(String[] args) {
int numberArray[] = { 120, 990, 121, 777, 808, 1280 };
for (int i = 0; i < numberArray.length; i++) {
printOnlyPalindrom(numberArray[i]);
}
}
private static void printOnlyPalindrom(int number) {
int finalNumber = 0;
int oldNumber = number;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and oldNumber both are same or not.
if (finalNumber == oldNumber)
System.out.println(finalNumber + " is a Palindrome.");
}
}

Output -

121 is a Palindrome.
777 is a Palindrome.
808 is a Palindrome.

How to Check Whether a Number Is a Palindrome in Java


In this article, we will see how to check if a number is palindrome or not. This is a very basic questions in interview. But, you never know about what kind of question the interviewer will ask. So, better you prepare for every certain questions. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 


Palindrome.java

package com.techbyteslearn.lab.basic;

public class Palindrome {

    public static void main(String[] args) {
        int number = 121;
        int temp = number;
        int finalNumber = 0;

        // Repeat the loop until the number becomes zero.
        while (number != 0) {

            // Get the last digit.
            int lastDigit = number % 10;

            // Build the reversed number.
            finalNumber = (finalNumber * 10) + lastDigit;

            // Remove the last digit from the number.
            number = number / 10;
        }

        // Compare the reversed number with the original number.
        if (finalNumber == temp) {
            System.out.println("This number is a Palindrome.");
        } else {
            System.out.println("This number is not a Palindrome.");
        }
    }
}

Output:

This number is a Palindrome.
 
 

One important correction from the original comments: % 10 gets the last digit, not the first digit. Also, number has already become 0 by the time of the final comparison, so comparing with temp is the correct approach.



Happy Learning.

Thursday, July 11, 2019

Find Duplicate Values in a List Using Java

In this article, we will see how to find the duplicate values from an array or list using java.  This is one of important programming questions in technical interview. Each interviewer has different approach to access the candidate. But, the logic and the approach by candidate is really matter. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see how to find the duplicate values from array. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).


DuplicateFinder.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicateFinder {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>(
                Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90));

        System.out.println("Input List Data = " + list);

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < list.size(); i++) {

            if (map.isEmpty()) {
                map.put(list.get(i), 1);
            } else if (map.containsKey(list.get(i))) {
                map.put(list.get(i), map.get(list.get(i)) + 1);
            } else {
                map.put(list.get(i), 1);
            }
        }

        System.out.println("\nDuplicate values are: ");

        // Iterate the Map and display the duplicate values.
        for (Entry<Integer, Integer> entry : map.entrySet()) {

            if (entry.getValue() > 1) {
                System.out.println(entry.getKey());

                // TODO: We can now put these values into any list.
            }
        }
    }
}

Output:

Input List Data = [4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90]

Duplicate values are:
4
5
25

Note- One small point: because HashMap does not guarantee iteration order, the order of 4, 5, and 25 in the output can vary.



Happy Learning.

Find the Largest Number in an Array Using Java

In this article, we will see how to find the largest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to find the smallest element from array. Now we will see how to find the largest number from integer array using java. 

The logic is very simple here, see the below.

  • At first we need to assume any element as largest value. Example - 0th location.
  • Then iterate over the array and compare with each element , whether its larger than the assumed larger value or not. If array element is larger then assign the array element value to assumed variable. Repeat the entire until end. 


FindLargestNumberInArray.java

package com.techbyteslearn.lab.basic;

public class FindLargestNumberInArray {

    // Find the largest value from an array.
    public static void main(String[] args) {
        int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150};

        // Assume the largest value is at the 0th index.
        int largest = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= largest) {
                largest = arr[i];
            }
        }

        System.out.println("Largest Number is ::" + largest);
    }
}

Output:

Largest Number is ::200

The original i < arr.length - 1 skips the last element. Using i < arr.length checks the complete array.


Using Java 8

int largest = IntStream.of(arr).boxed().max(Comparator.naturalOrder()).get().intValue() ;


 Happy Learning.

Find the Smallest Number in an Array Using Java


In this article, we will see how to find the smallest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find the smallest number from integer array using java. 


The logic is very simple here, see the below.

  • At first we need to assume the first smallest element.
  • Then iterate over the array and compare with each element , whether its smaller than the assumed value or not. If array element is smaller then assign the array element value to assumed variable. Repeat the entire until end. 

FindSmallestNumberInArray.java

package com.techbyteslearn.lab.basic;

public class FindSmallestNumberInArray {

    // Find the smallest value from an array.
    public static void main(String[] args) {
        int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150};

        // Assign the 0th index as the first smallest number.
        int smallest = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] <= smallest) {
                smallest = arr[i];
            }
        }

        System.out.println("Smallest Element is - " + smallest);
    }
}

Output:

Smallest Element is - 3

The original i < arr.length - 1 skips the last element. Using i < arr.length is the correct condition.



Using Java 8

IntStream.of(arr).boxed().min(Comparator.naturalOrder()).get().intValue();

Wednesday, July 10, 2019

Find One Missing Number from a List Using Java


In this article, we will see how to find the missing number from a list using java.  This is one of important common interview question asked in interview. You can see, how to find all missing numbers from a list. In this program we will use core java or the traditional way using for loop for finding the miss number from a list. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find one missing number using traditional core java style. 


The logic is very simple here, see the below.

  • At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number. 
  • Then , we need to calculate the sum of all those natural number.
  • Then we will subtract each element from the given list from sumOfNaturalNumbers.
  • Now, the at the last  the value inside sumOfNaturalNumbers is the missing number.

FindOneMissingNumber.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;

public class FindOneMissingNumber {

    public static void main(String[] args) {
        ArrayList<Integer> numberList = new ArrayList<>(
                Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));

        int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));

        for (int i = 0; i < numberList.size(); i++) {
            /*
             * Subtract each element from the list from sumOfNaturalNumbers.
             * The final value will be the missing number.
             */
            sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
        }

        int missingNumber = sumOfNaturalNumbers;
        System.out.println("Missing Number is :: " + missingNumber);
    }

    // Find the sum of all natural numbers up to limitNumber.
    private static int getSumUptoMax(int limitNumber) {
        int sum = 0;

        for (int i = 1; i <= limitNumber; i++) {
            sum = sum + i;
        }

        return sum;
    }

    // Find the greatest value from the list.
    private static int findMax(ArrayList<Integer> numberList) {
        int largest = numberList.get(0);

        for (int i = 1; i < numberList.size(); i++) {
            if (numberList.get(i) > largest) {
                largest = numberList.get(i);
            }
        }

        return largest;
    }
}

Output:

Missing Number is :: 12

 

This approach assumes the list contains the numbers from 1 through the maximum value, with exactly one number missing.


Happy Learning.

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());


Comparable vs Comparator in Java: Understanding the Comparable Interface


In this article we will see what is Comparable<T> interface ? How to use this interface with some sample examples ?

The Comparator interface is present inside java.util package. Its comparison function, which imposes a total ordering on some collection of objects. Its mostly used while sorting a collection of objects.  Means, it compares its two arguments for order.  Returns a negative integer,zero, or a positive integer as the first argument is less than, equal to, or greater than the second one.

The Comparators can be passed to a sort method (i.e. Collections.sort or Arrays.sort) to allow precise control over the sorting order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

This interface has one important method (Before JDK 8)  -

int compare(T o1, T o2);



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.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 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.techbyteslearn.lab.basic;
import java.util.Comparator;

public class EmployeeAgeComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}


EmployeeDeptComparator.java

package com.techbyteslearn.lab.basic;
import java.util.Comparator;

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.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Collections;

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]]


JAVA 8 

In JDK 8,  Comparator<T> is functional Interface. Its annotated with @FunctionalInterface and this comparator interface has added few more default & static methods. As its a functional interface therefore its will be used as the assignment target for a lambda expression or method reference.

Below are few examples :-

default Comparator<T> reversed()
default Comparator<T> thenComparing(Comparator<? super T> other)
default <U> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
default <U extends Comparable<? super U>> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor)
default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)



Here is the full list of methods added into Comparator<T> . We can use stream api of java 8 with lambda expression to implements comparator interface. We will see in the next subsequent posts on lambda expression and stream api.



Happy Learning.

Saturday, October 27, 2018

Filter Strings Using Stream API in Java


In this article we will learn how to use Java 8 Stream Filter with Example,  I have used String list to filter the names. Stream, A sequence of elements supporting sequential and parallel aggregate operations. Below example will show you how to filter the list with predicate.

StringFilterUsingStream.java

package com.techbyteslearn.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StringFilterUsingStream {

    public static void main(String[] str) {

        List<String> nameList = new ArrayList<String>();

        nameList.add("Roshna");
        nameList.add("Amit Kumar");
        nameList.add("Manoj");
        nameList.add("Neha");
        nameList.add("Rina");
        nameList.add("Ashna");
        nameList.add("Peter");
        nameList.add("Deb Kumar");

        System.out.println("All Names ::");
        nameList.stream().forEach(name -> System.out.println(name));

        // Filter all names ending with "Kumar"
        List<String> filteredList = nameList.stream()
                .filter(name -> name.endsWith("Kumar"))
                .collect(Collectors.toList());

        System.out.println("\nFiltered Names ::");
        filteredList.stream().forEach(name -> System.out.println(name));
    }
}

Output:

All Names :: Roshna Amit Kumar Manoj Neha Rina Ashna Peter Deb Kumar Filtered Names :: Amit Kumar Deb Kumar

I changed the comment from “ends with” to “ending with” and formatted the stream expression for readability. The program logic remains the same.


Hope this will help you. Happy Learning.



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.