Friday, July 31, 2020

How to implement our own Dynamic Array class in Java?

Oracle Java Exam Prep, Oracle Java Tutorial and Materials, Oracle Java Certification

Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList.

ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

◉ ArrayList elements are placed in contiguous storage so that they can be accessed and traversed using iterators.

◉ In ArrayList, data is inserted at the end.

◉ Inserting at the end takes differential time, as sometimes there may be a need of extending the array.

◉ Removing the last element takes only constant time because no resizing happens.

◉ Inserting and erasing at the beginning or in the middle is linear in time.

Functions to be implemented in the Dynamic array class:


Certain functions associated with the ArrayList that we will implement are:

1. void push(int data): This function takes one element and inserts it at the last. Amortized time complexity is O(1).

2. void push(int data, int index): It inserts data at the specified index. Time complexity is O(1).

3. int get(int index): It is used to get the element at the specified index. Time complexity is O(1).

4. void pop(): It deletes the last element. Time complexity is O(1).

5. int size(): It returns the size of the ArrayList i.e, number of elements in the ArrayList. Time complexity is O(1).

6. int getcapacity(): It returns the capacity of the ArrayList. Time complexity is O(1).

7. void print(): It is used to print array elements. Time complexity is O(N), where N is the size of the ArrayList.

Implementation of the Dynamic array class:


Oracle Java Exam Prep, Oracle Java Tutorial and Materials, Oracle Java Certification
Below is the implementation of our own ArrayList class.

// Java program to implement
// our own Dynamic Array class

import java.util.*;

// Self implementation of
// the ArrayList Class in Java
class ArrayListClass {

// arr is the array which stores
// our ArrayList elements
private int arr[];

// capacity is the total storage
// capacity of the ArrayList
private int capacity;

// current is the number of elements
// currently present in the ArrayList
private int current;

// Default constructor to initialise
// an initial capacity of 1 element and
// allocating storage using dynamic allocation
public ArrayListClass()
{
arr = new int[1];
capacity = 1;
current = 0;
}

// Function to add an element at the last
public void push(int data)
{

// if the number of elements
// is equal to the capacity,
// that means we don't have space
// to accommodate more elements.
// We need to double the capacity
if (current == capacity) {
int temp[] = new int[2 * capacity];

// copying old array elements
// to new array
for (int i = 0; i < capacity; i++)
temp[i] = arr[i];

capacity *= 2;
arr = temp;
}

// Inserting data
arr[current] = data;
current++;
}

// function to add element at any index
void push(int data, int index)
{

// if index is equal to capacity
// then this function is same
// as push defined above
if (index == capacity)
push(data);
else
arr[index] = data;
}

// Function to extract
// element at any index
int get(int index)
{

// if index is within the range
if (index < current)
return arr[index];

// if index is outside the range
return -1;
}

// function to delete last element
void pop()
{
current--;
}

// function to get size
// of the ArrayList
int size()
{
return current;
}

// function to get capacity
// of the ArrayList
int getcapacity()
{
return capacity;
}

// function to print ArrayList elements
void print()
{
for (int i = 0; i < current; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

// Driver program to check ArrayListClass
public static void main(String args[])
{
ArrayListClass v
= new ArrayListClass();
v.push(10);
v.push(20);
v.push(30);
v.push(40);
v.push(50);

System.out.println("ArrayList size: "
+ v.size());
System.out.println(
"ArrayList capacity: "
+ v.getcapacity());
System.out.println(
"ArrayList elements: ");
v.print();

v.push(100, 1);

System.out.println(
"\nAfter updating 1st index");

System.out.println(
"ArrayList elements: ");
v.print();
System.out.println(
"Element at 1st index: "
+ v.get(1));

v.pop();

System.out.println(
"\nAfter deleting the"
+ " last element");

System.out.println(
"ArrayList size: "
+ v.size());
System.out.println(
"ArrayList capacity: "
+ v.getcapacity());

System.out.println(
"ArrayList elements: ");
v.print();
}
}

Output:

ArrayList size: 5
ArrayList capacity: 8
ArrayList elements: 
10 20 30 40 50 

After updating 1st index
ArrayList elements: 
10 100 30 40 50 
Element at 1st index: 100

After deleting the last element
ArrayList size: 4
ArrayList capacity: 8
ArrayList elements: 
10 100 30 40

Wednesday, July 29, 2020

Difference between JDBC and Hibernate in Java

Oracle JDBC, Oracle Hibernate, Oracle Java Tutorial and Material, Oracle Java Exam Prep

Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let’s understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate.

Before getting into the differences, let us first understand what each of them actually means.

JDBC: JDBC stands for Java Database Connectivity. It is a java application programming interface to provide a connection between the Java programming language and a wide range of databases (i.e), it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.

Hibernate: Hibernate is an open-source, non-invasive, light-weight java ORM(Object-relational mapping) framework to develop objects which are independent of the database software and make independent persistence logic in all JAVA, JEE. It simplifies the interaction of java applications with databases. Hibernate is an implementation of JPA(Java Persistence API).

The following table describes the differences:

JDBC   HIBERNATE 
In JDBC, one needs to write code to map the object model’s data representation to the schema of the relational model.  Hibernate maps the object model’s data to the schema of the database itself with the help of annotations. 
JDBC enables developers to create queries and update data to a relational database using the Structured Query Language (SQL).  Hibernate uses HQL (Hibernate Query Language) which is similar to SQL but understands object-oriented concepts like inheritance, association etc. 
JDBC code needs to be written in a try catch block as it throws checked exception(SQLexception).  Whereas Hibernate manages the exceptions itself by marking them as unchecked. 
JDBC is database dependent i.e. one needs to write different codes for different database.  Whereas Hibernate is database independent and same code can work for many databases with minor changes. 
Creating associations between relations is quite hard in JDBC.  Associations like one-to-one, one-to-many, many-to-one, and many-to-many can be acquired easily with the help of annotations. 

Monday, July 27, 2020

Java String API regionMatches​()

Java String API regionMatches​(), Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Certification

Quick guide to Java String API regionMatches​() Method with Examples. This method is used to compare two sub strings. Syntax: public boolean regionMatches​(int toffset, String other, int ooffset, int len)

1. Java String regionMatches​() Overview


In this tutorial, We’ll learn about Java String API regionMatches​() method to compare two substrings. In other words, comparing regions of two strings.

This method is very handy when we want to compare portions of two strings. Instead of comparing all contents of Strings.

1.1 regionMatches() Syntax

public boolean regionMatches​(int toffset, String other, int ooffset, int len)
public boolean regionMatches​(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Fist variant does case sensitive comparison

Second variant has option to ignore the case. If true, it ignores case when comparing.

1.2 Parameters

toffset – the starting offset of the subregion in this string.

other – the string argument.

ooffset – the starting offset of the subregion in the string argument.

len – the number of characters to compare.

1.3 Returns

boolean

true if the specified subregion of this string exactly matches the specified
subregion of the string argument; false otherwise.

2. String regionMatches​() Examples


We’ll write a example programs using regionMatches​() method. It is very important to pass the parameters in order and with required values.

2.1 regionMatches​() Method Example

Below example program is written on regionMatches​ method. For this method, we must have to pass the parameters as below.

1st parameter: Start index of the current string. Comparison will start from this point.

2nd parameter: Takes another string which is to be compared.

3rd parameter: Start index of the another string.

4th parameter: How many characters to be compared.

String str1 = "welcome to java-w3schools blog";
String otherStr = "java";
boolean isMatch = str1.regionMatches(11, otherStr, 0, 4);

if (isMatch) {
 System.out.println("Substrings are matched");
} else {
 System.out.println("Substrings are not matched");
}

Output:

Substrings are matched

2.2 Case Ignore regionMatches​() Method Example

The below program does compare substrings by ignoring Case Type. We need to pass the additional parameter to enable case ignore.

// Example 2: Case Ignore
String str2 = "WELCOME TO JAVA-W3SCHOOLS BLOG";
String otherStr2 = "java";
isMatch = str2.regionMatches(true, 11, otherStr2, 0, 4);
 
if (isMatch) {
 System.out.println("Substrings are matched");
} else {
 System.out.println("Substrings are not matched");
}

Observe the above program. A boolean value is passed in 1st parameter. This parameter tells to JVM to ignore case.

Output:

Substrings are matched

3. String regionMatches​() Internal Code


regionMatches() method internal implementation code shown below.

public boolean regionMatches(int toffset, String other, int ooffset, int len) {
    byte tv[] = value;
    byte ov[] = other.value;
    // Note: toffset, ooffset, or len might be near -1>>>1.
    if ((ooffset < 0) || (toffset < 0) ||
         (toffset > (long)length() - len) ||
         (ooffset > (long)other.length() - len)) {
        return false;
    }
    if (coder() == other.coder()) {
        if (!isLatin1() && (len > 0)) {
            toffset = toffset << 1;
            ooffset = ooffset << 1;
            len = len << 1;
        }
        while (len-- > 0) {
            if (tv[toffset++] != ov[ooffset++]) {
                return false;
            }
        }
    } else {
        if (coder() == LATIN1) {
            while (len-- > 0) {
                if (StringLatin1.getChar(tv, toffset++) !=
                    StringUTF16.getChar(ov, ooffset++)) {
                    return false;
                }
            }
        } else {
            while (len-- > 0) {
                if (StringUTF16.getChar(tv, toffset++) !=
                    StringLatin1.getChar(ov, ooffset++)) {
                    return false;
                }
            }
        }
    }
    return true;
}

Java String API regionMatches​(), Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Certification
The result is false if and only if at least one of the following is true:

A) toffset is negative.

B) ooffset is negative.

C) toffset+len is greater than the length of this String object.

D) ooffset+len is greater than the length of the other argument.

E) There is some nonnegative integer k less than
len such that: this.charAt(toffset + k) != other.charAt(ooffset + k)

Later it compares char by char. If char mismatch it returns true, otherwise returns false.

public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len) {
        if (!ignoreCase) {
            return regionMatches(toffset, other, ooffset, len);
        }
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)length() - len)
                || (ooffset > (long)other.length() - len)) {
            return false;
        }
        byte tv[] = value;
        byte ov[] = other.value;
        if (coder() == other.coder()) {
            return isLatin1()
              ? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len)
              : StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len);
        }
        return isLatin1()
              ? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len)
              : StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len);
    }

If ignoreCase is false then it calls regionMatches(toffset, other, ooffset, len). If it is true then calls StringLatin1.regionMatchesCI() for LATIN Character Set.

It calls StringUTF16.regionMatchesCI() for UTF Character Set.

Wednesday, July 22, 2020

Ship your function

Now a days function as service(FaaS) is trending in serverless area and it is enabling new opportunity that allows to send function on the fly to server and it will start executing immediately. 

This is helps in building application that adapts to changing users needs very quickly.

Function_as_a_service is popular offering from cloud provider like Amazon , Microsoft, Google etc.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Study Matterials

FaaS has lot of similarity with Actor model that talks about sending message to Actors and they perform local action, if code can be also treated like data then code can also be sent to remote process and it can execute function locally. 

I remember Joe Armstrong talking about how during time when he was building Erlang he used to send function to server to become HTTP server or smtp server etc. He was doing this in 1986!

Lets look at how we can save executable function and execute it later.

I will use java as a example but it can be done in any language that allows dynamic linking. Javascript will be definitely winner in dynamic linking. 

Quick revision


Lets have quick look at functions/behavior in java

@Test
    public void square_number() {

        Function<Integer, Integer> sqr = x -> x * x;

        assertEquals(4, sqr.apply(2));
        assertEquals(9, sqr.apply(3));
        assertEquals(16, sqr.apply(4));
    }

    @Test
    public void to_upper() {

        Function<String, String> upper = x -> x.toUpperCase();
        assertEquals("FAAS", upper.apply("FaaS"));
    }

Nothing much to explain above code, it is very basic transformation.

Save function


Lets try to save one of these function and see what happens. 

@Test
   public void save_function() throws Exception {

       Function<String, String> upper = x -> x.toUpperCase();
       try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos)) {
           os.writeObject(upper);
       }
   }

Above code looks perfect but it fails at runtime with below error

java.io.NotSerializableException: faas.FunctionTest$$Lambda$266/1859039536 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at faas.FunctionTest.save_function(FunctionTest.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Lambda functions are not serializable by default.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Study Matterials

Java has nice trick about using cast expression to add additional bound, more details are available at Cast Expressions.

In nutshell it will look something like below

@Test()
    public void save_function_works() throws Exception {

        // Addtional casting allow to mark as serilized
        Function<String, String> upper = (Function<String, String> & Serializable) x -> x.toUpperCase(); 
         
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream os = new ObjectOutputStream(bos)) {

            os.writeObject(upper);

            try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                 ObjectInputStream in = new ObjectInputStream(bis)) {

                Function<String, String> restoredUpper = (Function<String, String>) in.readObject();

                Assertions.assertEquals("FAAS", restoredUpper.apply("FaaS"));
            }

        }
    }

This technique allows to convert any functional interface to bytes and reuse it later. It is used in JDK at various places like TreeMap/TreeSet as these data structure has comparator as function and also  supports serialization.

With basic thing working lets try to build something more useful.

We have to hide & Serialized magic to make code more readable and this can be achieved by functional interface that extends from base interface and just adds Serializable, it will look something like below

@FunctionalInterface
public interface SerFunction<T, R> extends Function<T, R>, Serializable {
}
 
@FunctionalInterface
public interface SerPredicate<T> extends Predicate<T>, Serializable {
}
 
....

Once we take care of boilerplate then it becomes very easy to write the functions that are Serialization ready.

List functions = asList(
                SerCode.f((Integer x) -> x * x),
                SerCode.f((String x) -> x.toUpperCase()),
                SerCode.p((String x) -> x.length() > 5)
        );
 
        byte[] code = saveFunction(functions);
        ObjectInputStream fStream = codeStream(code);
 
        List rFunctions = (List) fStream.readObject();
 
        int fIndex = 0;
        Function<Integer, Integer> rSquare = (Function<Integer, Integer>) rFunctions.get(fIndex++);
        System.out.println(rSquare.apply(10)); // Shows 100
 
        Function<String, String> rUpper = (Function<String, String>) rFunctions.get(fIndex++);
        System.out.println(rUpper.apply("FaaS")); // Shows "FAAS
 
        Predicate<String> rGt5Length = (Predicate<String>) rFunctions.get(fIndex++);
        System.out.println(rGt5Length.test("I am greater than 5")); // Shows true

With above building block we can save full transformation(map/filter/reduce/collect etc) and ship to sever for processing. This also allows to build computation that can recomputed if required.

Spark is distributed processing engine that use such type of pattern where  it persists transformation function and use that for doing computation on multiple nodes.

Monday, July 20, 2020

How to change procedural code into object-oriented one?

What style should Clean Code be written in?


Clean Code is not always object-oriented. Sometimes it will be written in procedural style. And what style is better: procedural or object-oriented? We should perform the choice under given conditions which facilitates its development and readability – in accordance with the principles of Clean Code.

Below is an example of the procedural code that will help me consider the purity of the code and its refactoring to the object oriented code.

public class Rectangle {
    double width;
    double height;
}
...
public class Geometry {
    double area(Object shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            return Math.PI * circle.radius * circle.radius
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            return rectangle.width * rectangle.height;
        } else if (shape instanceof Square) {
            Square square = (Square) shape;
            return square.size * square.size;
        }

        throw new IllegalArgumentException("Unknown shape");
    }
}

I choose the style in which the code will be written on the basis of observing the direction of changes that result from emerging new business requirements.

What changes does the procedural code allow?


If I mainly add new functions operating on already existing data structures, then the procedural code (new procedures) will probably remain legible. An example is the new function that returns the smallest rectangle containing given figure.

public class Geometry {
    Rectange containingRectange(Object shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            Rectangle rectangle = new Rectangle();
            rectangle.width = 2 * circle.radius;
            rectangle.height= 2 * circle.radius;
            return rectangle;
        } else if (shape instanceof Rectangle) {
            return (Rectangle) shape;
        } else if (shape instanceof Square) {
            ...
        }

        throw new IllegalArgumentException("Unknown shape");
    }
}

When will the procedural code become illegible?


But if you plan to add or modify existing data structures, it will force changes to all existing procedures. What happens when I decide to change the components in the Rectangle data structure to points describing 2 opposite corners of the square?

public class Point {
    double x,y; 
 
public class Rectangle {
     Point topLeft;
     Point bottomRight; 
}

It is not difficult to notice that such a change will force many changes to existing procedures. A way to avoid many changes (or minimize them) is to place the getX () and getY () methods in the Rectangle structure that will perform the necessary calculations.

public class Rectangle {
    private Point topLeft;
    private Point bottomRight;
 
    double getX(){
        return Math.abs(topLeft.x = bottomRight.x);
    }
 
    double getY(){
        return Math.abs(topLeft.y = bottomRight.y);
    }
}

But note that from that moment I start to hide details of the data structure. Details in the Rectangle class have been hidden and new methods calculate the necessary output. In this way, I am starting to change the code style from procedural to object oriented.

How to refactor a procedural code into an object-oriented one?


Perform self-encapsulation of data structures

At the beginning I add constructors and encapsulate details within data structures. In my case, the data in the structures are not changing, so the fields can be final.

public class Circle {
    private final double radius;
 
    public Circle(double radius) {
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
}

Define a common interface / base class for existing data structures

Next, I define an empty “Shape” base class that will expand all data structures. From now on, the “area” procedure accepts only the “Shape” abstract class extension as a parameter. Alternatively, it can also be a common interface.

public abstract class Shape{
}
 
public class Circle extends Shape {
    private final double radius;
 
    public Circle(double radius) {
        this.radius = radius;
    }
 
    public double getRadius() {
        return radius;
    }
}
 
...

Move the logic from the procedure to the base class

In order to transfer the logic to the base class, I will make a small modification to be able to use the method transfer in the IntelliJ tool.

public class Geometry {
    static double area(Shape shape) {
        return new Geometry().calculateArea(shape);
    }
 
    private double calculateArea(Shape shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            return Math.PI * circle.getRadius() * circle.getRadius();
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            return rectangle.getWidth() * rectangle.getHeight();
        } else if (shape instanceof Square) {
            Square square = (Square) shape;
            return square.getSize() * square.getSize();
        }
 
        throw new IllegalArgumentException("Unknown shape :" + shape.getClass());
    }
}

I obtained the above code by extracting a new method “calculateArea”, then deleting the word static and adding a call to the constructor.

Then I move the method containing the “calculateArea” logic from “Geometry” to the “Shape” base class.

public class Geometry {
    static double area(Shape shape) {
        return shape.calculateArea();
    }
}
 
public abstract class Shape {
    double calculateArea() {
        if (this instanceof Circle) {
            Circle circle = (Circle) this;
            return Math.PI * circle.getRadius() * circle.getRadius();
        } else if (this instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) this;
            return rectangle.getWidth() * rectangle.getHeight();
        } else if (this instanceof Square) {
            Square square = (Square) this;
            return square.getSize() * square.getSize();
        }
 
        throw new IllegalArgumentException("Unknown shape :" + getClass());
    }
}

After this distortion, there was a code smell: “base class is dependent on its derived classes”. Solving the problem will lead us to the next transformation.

Push method down

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

The transformation is fully automated in many environments like IntelliJ, Eclipse, NetBeans.

Delete unnecessary logic in derived classes


Finally, we finish with the transformation “replace conditional expressions with polymorphism”. In each of the subclasses (i.e. our old data structures), only one condition will be true.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

The final result of our refactoring is below

public class Circle extends Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    @Override
    double calculateArea() {
        Circle circle = (Circle) this;
        return Math.PI * circle.getRadius() * circle.getRadius();
    }
}

public class Geometry {
    static double area(Shape shape) {
        return shape.calculateArea();
    }
}

In addition, we can inline “Geometry.area” function and then change the name of “calculateArea” to “area”, so we come back to old naming.

Interpreter pattern

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

Friday, July 17, 2020

Java 8 Optional filter()

Oracle Java 8, Oracle Java Study Materials, Oracle Java Exam Prep, Oracle Java Tutorial and Material

A quick example guide to Java 8 Optional filter() Method. filter(Predicate predicate) method used to return a Optional object for the given predicate(the condition).

1. Overview


In this tutorial, We’ll discuss how to use Predicate with Optional class. The
Java 8 Optional class has a method filter() which takes Predicate as an argument.

Optional is a class and it is in java.util package. Optional is declared as final in its source code. Because no other classes can be inherited and to stop overriding the behavior.

API Note: If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.

First, let us take a look at syntax, it’s explanation, and example programs.

2. filter(Predicate predicate) Syntax


Below is the syntax for filter() method.

public Optional<T> filter(Predicate<? super T> predicate)

filter() method accepts Predicate as an argument and returns Optional value.

Oracle Java 8, Oracle Java Study Materials, Oracle Java Exam Prep, Oracle Java Tutorial and Material
Predicate Example:

Predicate takes one argument and returns boolean. Checks for a condition and returns true if condition satisfies else false.

Predicate<Employee> empSal = e -> e.getSal() > 10000;

This checks for the condition employee salary &gt; 10000.

3. Java 8 filter() Example for String


Below is the example program on filter() method.

In the example, first created an Optional instance by calling of() method with the string “Hello Mate, Welcome to oraclejavacertified blog”.

Next, created a predicate welcomePredicate to validate if the string contains the “Welcome” word in it. After this, using filter(welcomePredicate) method and passed welcomePredicate as an argument. When the filter() method is executed, welcomePredicate is evaluated. If welcomePredicate is true then it returns the current string.

In the next example, Created another Predicate haiPredicate to validate if the string contains “Hai”. Again called the Optional filter(haiPredicate) and evaluated haiPredicate. But no “Hai” text found. Hence, the condition in haiPredicate is failed. So it returned empty optional instance. because of this, the output is printed as “Optional.empty”.

package com.java.w3schools.blog.java8.optional;

import java.util.Optional;
import java.util.function.Predicate;

/**
 * java 8 Optional filter() method example
 *
 * @author Venkatesh
 *
 */
public class OptionalFilterExample {
 
 public static void main(String[] args) {
 
  Optional<String> helloOptonal = Optional.of("Hello Mate, Welcome to oraclejavacertified blog");
 
  // Predicate match case
  Predicate<String> welcomePredicate = s -> s.contains("Welcome");
  Optional<String> welcomeOptional = helloOptonal.filter(welcomePredicate);
  System.out.println("welcomeOptional : " + welcomeOptional);
 
  // Predicate non-match case
  Predicate<String> haiPredicate = s -> s.contains("Hai");
  Optional<String> haiOptional = helloOptonal.filter(haiPredicate);
  System.out.println("haiOptional : " + haiOptional);
 }
}

Output:

welcomeOptional : Optional[Hello Mate, Welcome to oraclejavacertified blog]
haiOptional : Optional.empty

4. filter() Example but Passing List to Optional 


In the above example, First created an Optional instance with String. In this example, Now we will create an Optional with List. We’ll see how
filter method behaves.

List<String> countries = Arrays.asList("USA", "UK", "AUS");
Optional<List<String>> countriesOptional = Optional.of(countries);

Predicate<List<String>> listPredicate = list -> list.stream().filter(name -> name.startsWith("U")).count() > 0;

Optional listOpional = countriesOptional.filter(listPredicate);
System.out.println("List Optional filter() : "+listOpional);

Output:

List Optional filter() : Optional[[USA, UK, AUS]]

5. Internal Implementation


Below is the internal implementation code from java 12 API.

public Optional<T> filter(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    if (!isPresent()) {
        return this;
    } else {
        return predicate.test(value) ? this : empty();
    }
}

Internally, it calls predicate.test(value) method where test() is a functional method.

Wednesday, July 15, 2020

The Collection Interface

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Study Materials

A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that takes a Collection argument. This constructor, known as a conversion constructor, initializes the new collection to contain all of the elements in the specified collection, whatever the given collection's subinterface or implementation type. In other words, it allows you to convert the collection's type.

Suppose, for example, that you have a Collection<String> c, which may be a List, a Set, or another kind of Collection. This idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in c.

List<String> list = new ArrayList<String>(c);

Or — if you are using JDK 7 or later — you can use the diamond operator:

List<String> list = new ArrayList<>(c);

The Collection interface contains methods that perform basic operations, such as int size(), boolean isEmpty(), boolean contains(Object element), boolean add(E element), boolean remove(Object element), and Iterator<E> iterator().

It also contains methods that operate on entire collections, such as boolean containsAll(Collection<?> c), boolean addAll(Collection<? extends E> c), boolean removeAll(Collection<?> c), boolean retainAll(Collection<?> c), and void clear().

Additional methods for array operations (such as Object[] toArray() and <T> T[] toArray(T[] a) exist as well.

In JDK 8 and later, the Collection interface also exposes methods Stream<E> stream() and Stream<E> parallelStream(), for obtaining sequential or parallel streams from the underlying collection.

The Collection interface does about what you'd expect given that a Collection represents a group of objects. It has methods that tell you how many elements are in the collection (size, isEmpty), methods that check whether a given object is in the collection (contains), methods that add and remove an element from the collection (add, remove), and methods that provide an iterator over the collection (iterator).

The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. Similarly, the remove method is designed to remove a single instance of the specified element from the Collection, assuming that it contains the element to start with, and to return true if the Collection was modified as a result.

Traversing Collections


There are three ways to traverse collections: (1) using aggregate operations (2) with the for-each construct and (3) by using Iterators.

Aggregate Operations

In JDK 8 and later, the preferred method of iterating over a collection is to obtain a stream and perform aggregate operations on it. Aggregate operations are often used in conjunction with lambda expressions to make programming more expressive, using less lines of code. The following code sequentially iterates through a collection of shapes and prints out the red objects:

myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));

Likewise, you could easily request a parallel stream, which might make sense if the collection is large enough and your computer has enough cores:

myShapesCollection.parallelStream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));

There are many different ways to collect data with this API. For example, you might want to convert the elements of a Collection to String objects, then join them, separated by commas:

    String joined = elements.stream()
    .map(Object::toString)
    .collect(Collectors.joining(", "));

Or perhaps sum the salaries of all employees:

int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));

These are but a few examples of what you can do with streams and aggregate operations.

The Collections framework has always provided a number of so-called "bulk operations" as part of its API. These include methods that operate on entire collections, such as containsAll, addAll, removeAll, etc. Do not confuse those methods with the aggregate operations that were introduced in JDK 8. The key difference between the new aggregate operations and the existing bulk operations (containsAll, addAll, etc.) is that the old versions are all mutative, meaning that they all modify the underlying collection. In contrast, the new aggregate operations do not modify the underlying collection. When using the new aggregate operations and lambda expressions, you must take care to avoid mutation so as not to introduce problems in the future, should your code be run later from a parallel stream.

for-each Construct

The for-each construct allows you to concisely traverse a collection or array using a for loop — see The for Statement. The following code uses the for-each construct to print out each element of a collection on a separate line.

for (Object o : collection)
    System.out.println(o);

Iterators

An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}

The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator instead of the for-each construct when you need to:

◉ Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.

◉ Iterate over multiple collections in parallel.

The following method shows you how to use an Iterator to filter an arbitrary Collection — that is, traverse the collection removing specific elements.

static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

This simple piece of code is polymorphic, which means that it works for any Collection regardless of implementation. This example demonstrates how easy it is to write a polymorphic algorithm using the Java Collections Framework.

Collection Interface Bulk Operations


Bulk operations perform an operation on an entire Collection. You could implement these shorthand operations using the basic operations, though in most cases such implementations would be less efficient. The following are the bulk operations:

◉ containsAll — returns true if the target Collection contains all of the elements in the specified Collection.

◉ addAll — adds all of the elements in the specified Collection to the target Collection.

◉ removeAll — removes from the target Collection all of its elements that are also contained in the specified Collection.

◉ retainAll — removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection.

◉ clear — removes all elements from the Collection.

The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation.

As a simple example of the power of bulk operations, consider the following idiom to remove all instances of a specified element, e, from a Collection, c.

c.removeAll(Collections.singleton(e));

More specifically, suppose you want to remove all of the null elements from a Collection.

c.removeAll(Collections.singleton(null));

This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element.

Collection Interface Array Operations


The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.

For example, suppose that c is a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c.

Object[] a = c.toArray();

Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c.

String[] a = c.toArray(new String[0]);

Monday, July 13, 2020

Java Compress/Decompress String/Data

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Java Learning, Java Certification

Java provides the Deflater class for general purpose compression using the ZLIB compression library. It also provides the DeflaterOutputStream which uses the Deflater class to filter a stream of data by compressing (deflating) it and then writing the compressed data to another output stream. There are equivalent Inflater and InflaterOutputStream classes to handle the decompression.

Compression


Here is an example of how to use the DeflatorOutputStream to compress a byte array.

//Compress byte arraystatic byte[] compressBArray(byte [] bArray) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();    try (DeflaterOutputStream dos = new DeflaterOutputStream(os)) {
        dos.write(bArray);    }
    return os.toByteArray();}

Let’s test:

//Testingbyte[] input = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".getBytes();byte[] op = CompressionUtil.compressBArray(input);System.out.println("original data length " + input.length + ",  compressed data length " + op.length);

This results ‘original data length 71,  compressed data length 12’

Decompression


public static byte[] decompress(byte[] compressedTxt) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();    try (OutputStream ios = new InflaterOutputStream(os)) {
        ios.write(compressedTxt);    }
 
    return os.toByteArray();}

Let’s test:

byte[] input = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".getBytes();byte[] op = CompressionUtil.compress(input);
 
byte[] org = CompressionUtil.decompress(op);
System.out.println(new String(org, StandardCharsets.UTF_8));

This prints the original ‘input’ string.

Let’s convert the byte[] to Base64 to make it portable


In the above examples we are getting the compressed data in byte array format (byte []) which is an array of numbers.

But we might want to transmit the compressed data to a file or json or db right? So, in order to transmit, we can convert it to Base64 using the following

{
    byte[] bytes = {}; //the byte array     String b64Compressed = new String(Base64.getEncoder().encode(bytes));
    byte[] decompressedBArray = Base64.getDecoder().decode(b64Compressed);    new String(decompressedBArray, StandardCharsets.UTF_8); //convert to original string if input was string }

Here’s the complete code and the test cases


package compress;
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.charset.StandardCharsets;import java.util.Base64;import java.util.zip.Deflater;import java.util.zip.DeflaterOutputStream;import java.util.zip.InflaterOutputStream;
public class CompressionUtil {
 
    public static String compressAndReturnB64(String text) throws IOException {
        return new String(Base64.getEncoder().encode(compress(text)));    }
 
    public static String decompressB64(String b64Compressed) throws IOException {
        byte[] decompressedBArray = decompress(Base64.getDecoder().decode(b64Compressed));        return new String(decompressedBArray, StandardCharsets.UTF_8);    }
 
    public static byte[] compress(String text) throws IOException {
        return compress(text.getBytes());    }
 
    public static byte[] compress(byte[] bArray) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();        try (DeflaterOutputStream dos = new DeflaterOutputStream(os)) {
            dos.write(bArray);        }
        return os.toByteArray();    }
 
    public static byte[] decompress(byte[] compressedTxt) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();        try (OutputStream ios = new InflaterOutputStream(os)) {
            ios.write(compressedTxt);        }
 
        return os.toByteArray();    }
 
}

Test case:

package compress;
import org.junit.jupiter.api.Test;
import java.io.IOException;import java.nio.charset.StandardCharsets;
public class CompressionTest {
 
    String testStr = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    @Test    void compressByte() throws IOException {
        byte[] input = testStr.getBytes();        byte[] op = CompressionUtil.compress(input);        System.out.println("original data length " + input.length + ",  compressed data length " + op.length);
        byte[] org = CompressionUtil.decompress(op);        System.out.println(org.length);        System.out.println(new String(org, StandardCharsets.UTF_8));    }
 
    @Test    void compress() throws IOException {
 
        String op = CompressionUtil.compressAndReturnB64(testStr);        System.out.println("Compressed data b64" + op);
        String org = CompressionUtil.decompressB64(op);        System.out.println("Original text" + org);
    }
 
}

Note: Since the compress and decompress method operate on byte[], we can compress/decompress any data type.

Friday, July 10, 2020

Hibernate and Spring Integration

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

We can simply integrate hibernate application with spring application.

In hibernate framework, we provide all the database information hibernate.cfg.xml file.

But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.

Advantage of Spring framework with hibernate


The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.

So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:

//creating configuration
Configuration cfg=new Configuration(); 
cfg.configure("hibernate.cfg.xml"); 
 
//creating seession factory object 
SessionFactory factory=cfg.buildSessionFactory(); 
 
//creating session object 
Session session=factory.openSession(); 
 
//creating transaction object 
Transaction t=session.beginTransaction(); 
     
Employee e1=new Employee(111,"arun",40000); 
session.persist(e1);//persisting the object 
 
t.commit();//transaction is commited 
session.close(); 

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this:

Employee e1=new Employee(111,"arun",40000); 
hibernateTemplate.save(e1);

Methods of HibernateTemplate class


Let's see a list of commonly used methods of HibernateTemplate class.

No. Method  Description 
void persist(Object entity)   persists the given object.
Serializable save(Object entity)   persists the given object and returns id. 
void saveOrUpdate(Object entity)   persists or updates the given object. If id is found, it updates the record otherwise saves the record.
void update(Object entity)   updates the given object.
void delete(Object entity)   deletes the given object on the basis of id. 
Object get(Class entityClass, Serializable id)   returns the persistent object on the basis of given id. 
Object load(Class entityClass, Serializable id)   returns the persistent object on the basis of given id. 
List loadAll(Class entityClass)   returns the all the persistent objects. 

Steps


Let's see what are the simple steps for hibernate and spring integration:

1. create table in the database It is optional.
2. create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
3. create Employee.java file It is the persistent class
4. create employee.hbm.xml file It is the mapping file.
5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
6. create InsertTest.java file It calls methods of EmployeeDao class.

Example of Hibernate and spring integration


In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of spring and hibernate example.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

1) create the table in the database

In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database

CREATE TABLE  "EMP558"   
   (    "ID" NUMBER(10,0) NOT NULL ENABLE,   
    "NAME" VARCHAR2(255 CHAR),   
    "SALARY" FLOAT(126),   
     PRIMARY KEY ("ID") ENABLE  
   )  
/  

2) Employee.java

It is a simple POJO class. Here it works as the persistent class for hibernate.

package com.oraclejavacertified;  
  
public class Employee {  
private int id;  
private String name;  
private float salary;  
  
//getters and setters  
  
}  

3) employee.hbm.xml

This mapping file contains all the information of the persistent class.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  
<hibernate-mapping>  
<class name="com.oraclejavacertified.Employee" table="emp558">  
          <id name="id">  
          <generator class="assigned"></generator>  
          </id>  
            
          <property name="name"></property>  
          <property name="salary"></property>  
</class>  
            
</hibernate-mapping>  

4) EmployeeDao.java

It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.

package com.oraclejavacertified;  
import org.springframework.orm.hibernate3.HibernateTemplate;  
import java.util.*;  
public class EmployeeDao {  
HibernateTemplate template;  
public void setTemplate(HibernateTemplate template) {  
    this.template = template;  
}  
//method to save employee  
public void saveEmployee(Employee e){  
    template.save(e);  
}  
//method to update employee  
public void updateEmployee(Employee e){  
    template.update(e);  
}  
//method to delete employee  
public void deleteEmployee(Employee e){  
    template.delete(e);  
}  
//method to return one employee of given id  
public Employee getById(int id){  
    Employee e=(Employee)template.get(Employee.class,id);  
    return e;  
}  
//method to return all employees  
public List<Employee> getEmployees(){  
    List<Employee> list=new ArrayList<Employee>();  
    list=template.loadAll(Employee.class);  
    return list;  
}  
}  

5) applicationContext.xml

In this file, we are providing all the informations of the database in the BasicDataSource object. This object is used in the LocalSessionFactoryBean class object, containing some other informations such as mappingResources and hibernateProperties. The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code of applicationContext.xml file.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

File: applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver"></property>  
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>  
        <property name="username" value="system"></property>  
        <property name="password" value="oracle"></property>  
    </bean>  
      
    <bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  
          
        <property name="mappingResources">  
        <list>  
        <value>employee.hbm.xml</value>  
        </list>  
        </property>  
          
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                  
            </props>  
        </property>  
    </bean>  
      
    <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">  
    <property name="sessionFactory" ref="mysessionFactory"></property>  
    </bean>  
      
    <bean id="d" class="com.oraclejavacertified.EmployeeDao">  
    <property name="template" ref="template"></property>  
    </bean>  
      
    </beans>  

6) InsertTest.java

This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.

package com.oraclejavacertified;  
  
import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
  
public class InsertTest {  
public static void main(String[] args) {  
      
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    EmployeeDao dao=(EmployeeDao)factory.getBean("d");  
      
    Employee e=new Employee();  
    e.setId(114);  
    e.setName("varun");  
    e.setSalary(50000);  
      
    dao.saveEmployee(e);  
      
}  

Enabling automatic table creation, showing sql queries etc.

You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's see the code:

<property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                  
            </props>  

If you write this code, you don't need to create table because table will be created automatically.