Sunday, 28 June 2015

Create Custom Linked List in Java


How to implement custom Linked List in java

Linked list is inbuilt class of collection framework. But for understanding of linked list we can create our own linked list and write some common methods of linked list like add, remove, size etc.

List is sequential data structure,  it is collection of nodes in linear fashion. One node have two fields first one is containing data or object and second one is reference to another node.

I have created inner Node class to represent node in custom linked list.

CustomLinkedList.java 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package com.javasuitor;

public class CustomLinkedList {
 // Author : Ashok singh
// head points to start of linked list
Node head; public CustomLinkedList() { head = new Node(null); } public void addAtLast(Object object) { Node newNode = new Node(object); Node temp = head; while (temp.getNext() != null) { temp = temp.getNext(); } // After loop temp will reach at end of list temp.setNext(newNode); } public void traverseList() { Node temp = head; if (temp.getNext() == null) { System.out.println("Underflow : List is empty"); System.exit(0); } while (temp.getNext() != null) { temp = temp.getNext(); System.out.println(temp.getObject().toString()); } } public void addAtIndex(Object object, int index) { Node temp = head; Node temp2 = null; Node newNode = new Node(object); // check for empty list if (temp.getNext() == null) { temp.setNext(newNode); return; } // Check for invalid index if (index > size() - 1) { System.out.println("Inserted Index does not exist in list"); System.exit(0); } for (int i = 0; i <= index; i++) { temp2 = temp; temp = temp.getNext(); } temp2.setNext(newNode); newNode.setNext(temp); } public int size() { Node temp = head; int count = 0; while (temp.getNext() != null) { count++; temp = temp.getNext(); } return count; } public void removeFromEnd(){ Node temp =head; Node temp2=null; // Check for Underflow if(temp.getNext()==null){ System.out.println("UnderFlow : List is empty"); System.exit(0); } while(temp.getNext()!=null){ temp2=temp; temp = temp.getNext(); } // temp points to last node and temp2 points just before to temp. temp2.setNext(null); } public void removeFromIndex(int index){ Node temp = head; Node temp2 =null; // Check for underflow if(temp.getNext()==null){ System.out.println("Underflow : List is empty"); return; } // Check for invalid index if(index > size()-1){ System.out.println("Wrong Input: Invalid index"); return; } for(int i=0;i<=index;i++){ temp2 = temp; temp=temp.getNext(); } temp2.setNext(temp.getNext()); temp.setNext(null); } private class Node { Node next; Object object; public Node(Object object) { // When Node will created its next pointer will be null, we will set // it according to our requirement. this.object = object; this.next = null; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } } }

CustomLinkedListDemo.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.javasuitor;

public class CustomLinkedListDemo { 
  // Author : Ashok singh
public static void main(String[] args) { CustomLinkedList customList = new CustomLinkedList(); customList.addAtLast(new Integer(10)); customList.addAtLast(new Integer(20)); customList.addAtLast(new Integer(30)); customList.addAtLast(new Integer(40)); System.out.println("Traverse Custom Linked List"); customList.traverseList(); // Add new object at existing index // We consider as index starts from 0 as standard customList.addAtIndex(25, 2); System.out.println("Traverse List, after adding 25 at index 2"); customList.traverseList(); customList.removeFromEnd(); System.out.println("Traverse List, after last node removed"); customList.traverseList(); customList.removeFromIndex(1); System.out.println("Traverse List, after 1st index node removed"); customList.traverseList(); System.out.println("Size of Custom Linked List "+customList.size()); } }
Output : 

Traverse Custom Linked List
10
20
30
40
Traverse List, after adding 25 at index 3
10
20
25
30
40
Traverse List, after last node removed
10
20
25
30
Traverse List, after 1st index node removed
10
25
30
Size of Custom Linked List 3




Diagrams help to understand linked list operation

Custom Linked List Logical Structure
Custom Linked List logical structure



Add new element at the end of list
Add new element at the end of list
                               
Add new element at given index
Add new element at given index


I hope you understand how to implement custom linked list in java. I feel happy to discuss. Please post your query in comment.

Happy learning.  

Saturday, 23 May 2015

HashMap Of Java Collection With Easy Example

java.util.HashMap<K,V>   is used to implement Map data structure.It extends AbstractMap class , and implements Map interface.Internally HashMap use hash table to store objects. 

Characteristics of HashMap  

1. HashMap store objects as Key value Pair.
2. We can get value by its unique key.
3. HashMap can store only one null value as a key. 
4. HashMap is not thread safe, Multiple thread can access one HashMap simultaneously
5. HashMap does not maintain the order. 

Example HashMap<K,V> 



package com.javasuitor.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {

 public static void main(String[] args) {
  
  // Map contains data in  Key, Value Pair, keys will be unique
  Map<Integer,String> studentMap = new HashMap<Integer,String>();
  
  studentMap.put(101, "Ashok Singh");
  studentMap.put(102, "Arvind");  
  studentMap.put(103, "Monika");
  studentMap.put(104, "Aakanksha");
  studentMap.put(105, "Sourabh");  
  
  // We can pass null as a key only once in map.
  studentMap.put(null,null);
  
  // If you pass duplicate key then value will be overwritten. 
  
  studentMap.put(null,"No name");
  
  Set<Integer> keys = studentMap.keySet();
  
  // View all values
  for(Integer i : keys){
   System.out.println("Key :" + i +" Value : "+ studentMap.get(i));
  }
    
  
 }
}

Output :




Key :null Value : No name
Key :102 Value : Arvind
Key :103 Value : Monika
Key :101 Value : Ashok Singh
Key :104 Value : Aakanksha
Key :105 Value : Sourabh




Difference Between HashTable and HashMap


HashTable is very similar to HashMap. Difference between HashTable and HashMap are :

1. HashTable can not store null value.

2. HashTable is thread safe, multiple thread cannot access HashTable simultaneously.
3. HashMap is faster than HashTable.


Reference :

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html


Sunday, 10 May 2015

Comparator Interface of Java Collection with Example

Comparator Interface


In my previous post Sorting of Objects using Comparable Interface With Very Easy Example ,I sorted Student type objects according to roll number.

Now scenario is you are writing a program in which you wants to create three sets of Student objects , one should sort according to roll number , one should sort according to name and one should sort according to percentage. 

You can't use Comparable Interface here because by using comparable we can define only one order of sorting. To meet our specification we have to use comparator interface.

Comparator Interface have two methods compare() and equal(). We can pass Comparator reference as a parameter of Tree Set constructor.

Let's understand with example.
I have one Student POJO class.

Student.java 




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.javasuitor.bean;

import java.util.Comparator;


public class Student{

 private int rollNo;
 private String name; 
 private double percentage;
 
 public Student() {
  // TODO Auto-generated constructor stub
 }
 
 public Student(int rollNo, String name, double percentage) {
  super();
  this.rollNo = rollNo;
  this.name = name;
  this.percentage = percentage;
 }

 public int getRollNo() {
  return rollNo;
 }


 public void setRollNo(int rollNo) {
  this.rollNo = rollNo;
 }


 public String getName() {
  return name;
 }


 public void setName(String name) {
  this.name = name;
 }


 public double getPercentage() {
  return percentage;
 }


 public void setPercentage(double percentage) {
  this.percentage = percentage;
 }

 
 @Override
 public boolean equals(Object object) {  
  // we need to type cast Object into Student type.
  Student student = (Student)object; 
  
  if(this.rollNo == student.rollNo)
   return true;
  else
   return false;
 }
 

 @Override
 public int hashCode() {
  // hash code will be roll number of student.
  return this.rollNo;
 }
 
 public static Comparator<Student> rollNumberComparator = new Comparator<Student>() {
  @Override
  public int compare(Student s1, Student s2) {
   // TODO Auto-generated method stub
   return s1.getRollNo()-s2.getRollNo();
  }
 };
 
 public static Comparator<Student> nameComparator = new Comparator<Student>() {
  @Override
  public int compare(Student s1, Student s2) {
   // TODO Auto-generated method stub
   return s1.getName().compareTo(s2.getName());
  }
 };
 

}

I have created two comparator one will sort according to roll number and one will sort according to name.

Now check demo class


StudentTreeSetDemo.java






 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.javasuitor.demo;

import java.util.Iterator;
import java.util.TreeSet;

import com.javasuitor.bean.Student;

public class StudentTreeSetDemo {

 public static void main(String[] args) {
  // This Tree Set store Student objects according to order of name
  TreeSet<Student> studentSet1 = new TreeSet<Student>(
    Student.nameComparator);

  // This Tree Set store Student objects according to order of roll number
  TreeSet<Student> studentSet2 = new TreeSet<Student>(
    Student.rollNumberComparator);

  //
  Student s1 = new Student(101, "Ashok", 82.2);
  Student s2 = new Student(102, "Jony", 80.3);
  Student s3 = new Student(103, "Devang", 76.0);
  Student s4 = new Student(104, "Sourabh", 74.2);
  Student s5 = new Student(105, "Aakash", 78.33);

  // Adding five objects into studentSet1
  studentSet1.add(s1);
  studentSet1.add(s2);
  studentSet1.add(s3);
  studentSet1.add(s4);
  studentSet1.add(s5);

  // Adding same five objects into studentSet2
  studentSet2.add(s1);
  studentSet2.add(s2);
  studentSet2.add(s3);
  studentSet2.add(s4);
  studentSet2.add(s5);

  // Print Students details

  System.out.println("Students in student Set 1 sorted according to name\n" );
  Iterator<Student> studentIterator1 = studentSet1.iterator();
  while (studentIterator1.hasNext()) {
   Student s = studentIterator1.next();
   System.out.println("Roll No: " + s.getRollNo() + " Name: "
     + s.getName() + " Percentage: " + s.getPercentage());

  }
  
  
  System.out.println("\n\nStudents in student Set 2 sorted according to roll number\n");
  Iterator<Student> studentIterator2 = studentSet2.iterator();
  while (studentIterator2.hasNext()) {
   Student s = studentIterator2.next();
   System.out.println("Roll No: " + s.getRollNo() + " Name: "
     + s.getName() + " Percentage: " + s.getPercentage());

  }
  

 }

}

We created two set studentSet1 and studentSet2 . They both have same data but in different order. 
Let's check output of program


OUTPUT



Students in student Set 1 sorted according to name
Roll No: 105 Name: Aakash Percentage: 78.33
Roll No: 101 Name: Ashok Percentage: 82.2
Roll No: 103 Name: Devang Percentage: 76.0
Roll No: 102 Name: Jony Percentage: 80.3
Roll No: 104 Name: Sourabh Percentage: 74.2


Students in student Set 2 sorted according to roll number
Roll No: 101 Name: Ashok Percentage: 82.2
Roll No: 102 Name: Jony Percentage: 80.3
Roll No: 103 Name: Devang Percentage: 76.0
Roll No: 104 Name: Sourabh Percentage: 74.2
Roll No: 105 Name: Aakash Percentage: 78.33


I hope you understood the Comparator interface.

Please feel free to ask any question.


Happy learning.... :)






Sorting of Objects using Comparable Interface With Very Easy Example

Comparable Interface

What is Comparable Interface in java collection

I explained TreeSet class which stored Integer numbers. You have seen TreeSet stored Integer numbers in ordered way. 
Now think about the scenario you want to store Object of your class into TreeSet. In my case I have a Student class and I have five objects of type Student, Now I want to store these objects in TreeSet. 

The matter of discussion is we know that TreeSet store objects in ordered way. How TreeSet will come to know the order of Student type objects.Here the order might be according to student roll number, student name, student percentage etc.

We have to define the order by implementing the Comparable Interface.

Comparable Interface have a method compareTo() which compare one object to another object. It returns positive integer number if current object which invoked method is greater than object which is passed as parameter, negative integer if  current object which invoked method is smaller than object which is passed as parameter,
and zero if both equal.

Suppose I want to store objects of Student type according to roll number, then I have to implement Comparable interface and override the compareTo method.

Please go thorough example.

Student.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.javasuitor.bean;


public class Student implements Comparable{

 private int rollNo;
 private String name; 
 private double percentage;
 
 public Student() {
  // TODO Auto-generated constructor stub
 }
 
 public Student(int rollNo, String name, double percentage) {
  super();
  this.rollNo = rollNo;
  this.name = name;
  this.percentage = percentage;
 }

 public int getRollNo() {
  return rollNo;
 }


 public void setRollNo(int rollNo) {
  this.rollNo = rollNo;
 }


 public String getName() {
  return name;
 }


 public void setName(String name) {
  this.name = name;
 }


 public double getPercentage() {
  return percentage;
 }


 public void setPercentage(double percentage) {
  this.percentage = percentage;
 }

 
 @Override
 public boolean equals(Object object) {  
  // we need to type cast Object into Student type.
  Student student = (Student)object; 
  
  if(this.rollNo == student.rollNo)
   return true;
  else
   return false;
 }
 

 @Override
 public int hashCode() {
  // hash code will be roll number of student.
  return this.rollNo;
 }
 
 @Override
 public int compareTo(Object object) {
  Student s = (Student) object;  
  return this.rollNo - s.rollNo;
 }

}

StundentTreeSetDemo.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javasuitor.demo;

import java.util.Iterator;
import java.util.TreeSet;

import com.javasuitor.bean.Student;

public class StudentTreeSetDemo {
 
 public static void main(String[] args) {
  TreeSet<Student> studentSet = new TreeSet<Student>();
  
  Student s1 = new Student(101,"Ashok",82.2);
  Student s2 = new Student(102,"Bibin",80.3);
  Student s3 = new Student(103,"Devang",76.0);
  Student s4 = new Student(104,"Sourabh",74.2);
  Student s5 = new Student(105,"Ravi",78.33);
  
  studentSet.add(s1);
  studentSet.add(s2);
  studentSet.add(s3);
  studentSet.add(s4);
  studentSet.add(s5);
  
  // Print Students details
  
  System.out.println("Students in student Set");
  Iterator<Student> studentIterator = studentSet.iterator();
  while (studentIterator.hasNext()) {
   Student s = studentIterator.next();
   System.out.println("Roll No: "+s.getRollNo() +" Name: "+s.getName()+" Percentage: "+s.getPercentage());
      
  }
  
  
 }

}


OutPut


 Define order of Object in TreeSet

You can see in output all objects are arranged according to roll number. I hope you understood the functionality of TreeSet.


Please feel free to ask any question.


Happy learning. 


Saturday, 9 May 2015

TreeSet in Java Collection With Very Basic Example

What is TreeSet in java collection

Before going deep in TreeSet please give 2 minutes for getting
introduction of Set interface .

The Java platform contains three general 

purpose Set implementations: HashSetTreeSet, and LinkedHashSetHashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSetLinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). 

java.util.TreeSet<E> extends java.util.AbstractSet<E> class. It implements Serializable, Set, SortedSet interface. TreeSet is also representation mathematical  Set. But TreeSet store elements in ordered way. Whenever we want to store objects in set in ordered way we use TreeSet.


Use Of TreeSet

1. Its contains unique values.
2. It store objects in ordered way.
3. Access and retrieval times are quite fast.

Example :

In this example we will see how TreeSet manage order. For Integer, String, Double Tree set store in ascending order.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.javasuitor.demo;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * @author Ashok
 * 
 */
public class TreeSetDemo {
 public static void main(String[] args) {
  TreeSet<Integer> numberSet = new TreeSet<Integer>();

  numberSet.add(10);
  numberSet.add(4);
  numberSet.add(2);
  numberSet.add(9);
  numberSet.add(8);
  numberSet.add(3);
  numberSet.add(7);
  numberSet.add(6);
  numberSet.add(5);
  numberSet.add(1);

  // Traverse TreeSet
  System.out.println("Elements in TreeSet");
  for (Integer i : numberSet) {
   System.out.println(i);
  }

  // Another way to traverse TreeSet
  System.out.println("Traverse by Iterator");
  Iterator<Integer> iterator = numberSet.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

 }

}


OUTPUT :

Elements in TreeSet
1
2
3
4
5
6
7
8
9
10
Traverse by Iterator
1
2
3
4
5
6
7
8
9
10


You can see in output all numbers are arranged in ascending order. I hope you understood the basic functionality of TreeSet.

In next blog I will dive u deep into TreeSet. Don't worry its does require additional oxygen supply :)


Please feel free to ask any question.


Happy learning.