Friday, 14 October 2016

Reversing a Linked List


There are multiple ways of solving this problem  :

1. Using Recursion in the O(n) time & O(n) space complexity: 


 /**
 * @author sachin
 *
 */
public class LinkedListDemo {
static Node head;
static class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
static void printList(Node head){
while(head!=null){
System.out.println(head.data + " ");
head = head.next;
}
}
static void recursiveReverse(Node head)  {
//Base condition
if(head ==null ){
return;
}
recursiveReverse(head.next);
System.out.println(head.data + " ");
}
public static void main(String[] args) {
LinkedListDemo.head = new Node(25);
LinkedListDemo.head.next = new Node(35);
LinkedListDemo.head.next.next = new Node(14);
LinkedListDemo.head.next.next.next = new Node(12);
System.out.println("Original Linked list is :");
LinkedListDemo.printList(head);
System.out.println("Reversed linked list : ");
LinkedListDemo.recursiveReverse(head);
}
}
Output:
Original Linked list is :
25 
35 
14 
12 
Reversed linked list : 
12 
14 
35 
25 

2. Using Iteration  in time O(n) & space O(1) complexity : 

This approach follows takes 3 Nodes   current[head node] , next and previous , head node is looped to move forward and prev node follows it as below :

Before iteration :

head --> 1 --> 2 --> 3 --> 4 --> 5--> null


Node current = head;
Node next = null;
Node prev = null;
//iterate the head node to the end or till the null is found

while(current!=null){
next = current.next;  //get the next node N
current.next=prev;  //next node N assigned the value of prev node
prev = current; //prev node is assigned to current node
current = next; // current node is assigned to next node 
}
head = prev;  //head is assigned to prev node which has the node detail in reverse order 


After iteration :


null <--1 <-- 2 <-- 3 <-- 4 <-- 5  <--- head



  
/**
 * @author sachin
 *
 */
public class LinkedListDemo {
static Node head;
static class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
static Node reverse(Node head){
Node current = head;
Node next = null;
Node prev = null;
while(current!=null){
next = current.next;
current.next=prev
prev = current;
current = next;
}
head = prev;
return head;
}
static void printList(Node head){
while(head!=null){
System.out.println(head.data + " ");
head = head.next;
}
}
public static void main(String[] args) {
LinkedListDemo.head = new Node(25);
LinkedListDemo.head.next = new Node(35);
LinkedListDemo.head.next.next = new Node(14);
LinkedListDemo.head.next.next.next = new Node(12);
System.out.println("Original Linked list is :");
LinkedListDemo.printList(head);
System.out.println("Reversed linked list : ");
head = LinkedListDemo.reverse(head); //getting the head node after reversal
LinkedListDemo.printList(head);
}
}
Output : 

Original Linked list is :
25 
35 
14 
12 
Reversed linked list : 
12 
14 
35 
25 


Enjoy the coding !!!

Tuesday, 11 October 2016

Lambda expression in Java 8


Lambda expressions, also known as closures, function literals, or simply lambdas
Lambda expression is being one of the biggest feature of the Java 8 that are massively increasing the capability  of Java to functional programming . Its use is very simple to use at the same time easy to simple to understand.

Its look like :

     functional interface =   parameter --> expression body  gives output of the expression operation

(arg1, arg2...) -> { body }

(type1 arg1, type2 arg2...) -> { body }

Following are some examples of Lambda expressions.
(int a, int b) -> {  return a + b; }

() -> System.out.println("Lambda Expression unveiled");

(String s) -> { System.out.println(s); }

() -> 30

() -> { return 3.1415 };


  • Lambda expression is being mainly used to define the inline implement of a functional interface which is having only one  method.
  • Lambda expression eliminates the need of anonymous interface and define an inline implementation of the functional interface.
  • Any interface can have a lambda expression associated with it if satisfies the following 3 conditions ->:
  1. Interface must be a functional interface i.e., its should have only one method.
  2. Number of parameters in the lambda expression must match the number of parameters of the functional interface single method.
  3. Return type of the lambda expression must match the return type of single interface method.
  • we can annotate the interface with @FunctionalInterface, a new annotation for Java 8 that says we have a functional interface
  • Just like in the javascript , function are treated as an first order function and are treated as a part of functional programming , same is the lambda expression are treated in the Java8.


In the Javascript function are not mandatory to have a return value and can have only expression body E.g. ,

function mathOperation(a , b){
}

There are 4 type of lambda expressions  is presented as follows :


       
1. With type declaration 
(int a, int b) -> a + b; 
2. Without type declaration
 (a, b) -> a - b; 
3. With return statement along with curly braces
 (int a, int b) -> { return a * b; };

4. Without return statement and without curly braces.
(int a, int b) -> a / b;



  • A lambda expression  is essentially an object , one can assign this object to a variable and pass the lambda expression for other operation. 
Example1

public class LambdaExpression  {
@FunctionalInterface
public interface NumberComparator {
public boolean compare(int a1, int a2);
}
public static void main(String[] args) {
NumberComparator numberComparator = (a1, a2) -> {return a1 > a2;};
boolean result = numberComparator.compare(4, 3);
System.out.println("result=" + result);
}
}
Output: 

result=true


Example2 :  Sorting on the List of a class Employee


/**
 * @author sachin
 *
 */
class Employee{
String name;
Integer age;
Employee(String name,Integer age){
this.name = name;
this.age = age;
}
}
public class LambdaExpression  {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<>();
empList.add(new Employee("John", 23));
empList.add(new Employee("Adam", 26));
empList.add(new Employee("Rollins", 28));
empList.add(new Employee("Richard", 26))
// old way of sorting  on name using anonymous class
System.out.println("--- sorting on the name using anonymous class using comparator --- ");
Collections.sort(empList, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
});
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
// new way of sorting  on name using lambda expression
System.out.println("\n--- sorting on the age using lambda expression with type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the age using lambda expression without type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, ( e1 , e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the name using sort of the List and lambda expression --- ");
//Anonymous Inner class replaced with Lambda expression without type declaration and sorting on name
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
empList.sort((e1,e2) -> e1.name.compareTo(e2.name));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
}
}
Output : 
--- sorting on the name using anonymous class using comparator --- 

Adam 26
John 23
Richard 26
Rollins 28
--- sorting on the age using lambda expression with type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the age using lambda expression without type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the name using sort of the List and lambda expression --- 
Adam 26
John 23
Richard 26
Rollins 28
------------------------------------------      


Lambda expression is a brilliant feature added in the Java to remove the uses of anonymous class and make a robust feature towards functional programming. Functional interfaces which is another great feature added in the Java makes the lambda expression more useful and easy to understand .

Enjoy the Lambda expression !!!!

Saturday, 8 October 2016

com.mongodb.MongoInternalException: org.springframework.dao.InvalidDataAccessResourceUsageException

Exception in the mongoDB related document  size : 
------------------------------------------------------------------------------------------------------------------

com.mongodb.MongoInternalException: Size 19534568 is larger than MaxDocumentSize 16793600.
org.springframework.dao.InvalidDataAccessResourceUsageException: Size 19534568 is larger than MaxDocumentSize 16793600.; nested exception is com.mongodb.MongoInternalException: Size 19534568 is larger than MaxDocumentSize 16793600.
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:77)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:460)
at org.springframework.data.mongodb.core.MongoTemplate.doUpdate(MongoTemplate.java:1077)
at org.springframework.data.mongodb.core.MongoTemplate.updateFirst(MongoTemplate.java:1051)
--------------------------------------------------------------------------------------------------------------------------------

Solution : Above mentioned exceptions occurred when your document size exceeds the default BSON size limit of 16 MB and MongoDB supports no more than 100 levels of nesting for BSON documents in Mongo 3.0. [reference]

Its being made limited to avoid excessive use of RAM or during data transfers avoiding excessive bandwidth  consumption of the network. But 16 MB is still good number to store documents in a collection. 

Note :  A record in a MongoDB collection and the basic unit of data in MongoDB. Documents are analogous to JSON objects but exist in the database in a more type-rich format known as BSON.

Going beyond storing the BSON threshold limit , if one require to store say 100 MB or 2.5 GB  size of file [as in case of Video, Audio streaming files etc] then MongoDB provides a way to solve this challenge.  GridFS  API feature is one of the main  and  brilliant feature of MongoDB. Using this one can store any huge size of data as its stored the file into chunks of 255KB and store the file in the DB.


When to Use GridFS

In MongoDB, use GridFS for storing files larger than 16 MB.
In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem.
  • If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.
  • When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory.
  • When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities, you can use GridFS. When using geographically distributed replica sets, MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities.
Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove previous versions if needed.
Furthermore, if your files are all smaller the 16 MB BSON Document Size limit, consider storing the file manually within a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.


Check the Max size of BSON  : We can check it on Mongo Shell by issuing following command

db.isMaster().maxBsonObjectSize/(1024*1024);


Enjoy the coding and MongoDB!!!

Friday, 7 October 2016

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: 
Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext

Above exception occurs when we start the tomcat server and shows the state of conflicting of jars in the library or dependencies.

Usually adding  commons-digester3-3.2.jar from Apache Commons Digester. If you are using Maven you can add will solve the issue.
<dependency>
    <groupId>commons-digester</groupId>
    <artifactId>commons-digester</artifactId>
    <version>2.1</version>
</dependency>
But if your project having common.logging jars along with commons-digestor library 
this exception would again.

So you need to remove common.logging jars from the library or pom.xml from the project.

Same I have tried and worked perfectly  and tomcat was starting successfully.