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. 

Saturday, 2 May 2015

#05 How equlas() and hashCode() mehtods work - java.


What are equals and hashCode method do?

Equals and hashCode in Java are two fundamental method which is declared in Object class and part or core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object.


In my previous post Easy way to understand HashSet , I described HashSet does not allow duplicate value. 
But think about scenario I have a Student class.

Student POJO Class

I am creating two objects of student.
checking output of equals method

Now look at the output

output of equals method

Wheteher roll numbers ,fname ,lname are same for both objects output is false.
whenever we use == operator for object or equals to method for object. java check whether two reference pointing same memory location or not. if they are not pointing same memory, java consider it as two different objects. 

In this scenario HashSet also add s1 and s2. But it is wrong according to user view.

Here we need to change default behaviour of java equals method. 

So we need to override the equals method of object class and custmize it to our requirement.

I am adding two method in my Student class.

We are adding hashCode method also,because equals object must have same hash code.

Now run the application and look at the output :


It is common practise that whenever we want to add Class object to HashSet, TreeSet,ArrayList, or any java collection we override equals() and hashCode method.

Next ... 
In my next post I will explain functionality of TreeSet.

Hope it will help full.