Thursday, 13 December 2012

Iterate through HashMap


Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}


If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;
for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():
for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

Source;- stackoverflow

Example Code:-

MapIteration.java
package collection.iteration;

import java.util.*;
import java.util.Map.Entry;

public class MapIteration {

public static void main(String[] args) {
Map <String,Employee> map= new HashMap<String,Employee>();
Employee emp1= new Employee(25, "Hitesh");
Employee emp2= new Employee(26, "Rajan");
Employee emp3= new Employee(27, "Dinesh");
Employee emp4= new Employee(24, "Neha");

map.put("e1",emp1);
map.put("e2",emp2);
map.put("e3",emp3);
map.put("e4",emp4);
System.out.println(map.keySet()); // Displaying all keys
System.out.println(map.values()); // Displaying all values
for(Map.Entry<String, Employee> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}

}
And
 Employee.java


package collection.iteration;

public class Employee implements Comparable<Employee> {
int age;
String name;

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

}
public String toString(){
return("The age is "+age+" and the name is "+name);
}

public int compareTo(Employee e){
return name.compareTo(e.name);
}
}


 Output:

[e3, e4, e1, e2]
[The age is 27 and the name is Dinesh, The age is 24 and the name is Neha, The age is 25 and the name is Hitesh, The age is 26 and the name is Rajan]
e3
The age is 27 and the name is Dinesh
e4
The age is 24 and the name is Neha
e1
The age is 25 and the name is Hitesh
e2
The age is 26 and the name is Rajan




Regards
Rajan Bansal

When hashSet and equals methods executes

class Person
{
    String name;

    Person(String n)
    {
        name=n; 
    }
    public String getName()
    {
        return name;   
    }

    @Override
    public boolean equals(Object arg0) {

        System.out.println("in equals");

        Person obj=(Person)arg0;

        System.out.println("1st "+getName());
        System.out.println("2nd "+obj.getName());

        if(this.getName().equals(obj.getName()))
        {
                return true;
        }
        return false;
    }


    @Override
    public int hashCode() {

        System.out.println("in hash code");
        System.out.println(" value is "+Integer.valueOf(name.charAt(0)));
        return Integer.valueOf(name.charAt(0));
    }
}

In main I have the following code

Person obj1=new Person("bcd");

Person obj2=new Person("cde");

Person obj3=new Person("abc");

Person obj4=new Person("abc");

Now if I add these objects to hashset

Set<Person> sset=new HashSet<Person>();

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj3);

I am getting this output

in hash code                                                                      
value is 98    
in hash code   
value is 97    
in hash code    
value is 99    
in hash code    
value is 97  
in equals  
1st abc     
2nd abc

Question 1 : why equals() function is called only once for checking obj3 and obj4 ? Why its not checked for rest of the objects ?

Question 2 : If the answer is because they both have same hash code,only then equals will be called, then why its not called for below code

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj4);
output is :

in hash code  
value is 98  
in hash code   
value is 97   
in hash code   
value is 99   
in hash code  
value is 97 
It's not going inside equals() method even though two same objects are added to hash set which has same hash code.

Question 4 :I iterated the above value and printed the contents but neither hashcode nor equals were called. when its really useful to override hashcode and equals method ?

Question 3 : when hash code and equals will be called ?


Answers:

1.There's no need to call equals if hashCode differs
2.There's no need to call hashCode if (obj1 == obj2)
3.There's no need for hashCode and/or equals just to iterate - you're not comparing objects
4. When needed to distinguish in between objects.


Source: stackoverflow

Regards
Rajan Bansal

Tuesday, 11 December 2012

What is MVC framework using Spring


The MVC is a standard software architecture that aims to separate business logic from presentation logic, enabling the development, testing and maintenance of both isolated .

The picture below depicts the flow of information in the MVC pattern :


(1) The user triggers an event through the UI (click a button on the page or something).
(2) The controller receives the event and coordinates how things will happen on the server side, i.e. the flow goes to the objects required to perform the business rule.
(3) The model is used to represent the business information so it is called by the controller to perform the business rule that should be done. The model can also be used to send data to the view layer.
(4) After the controller performs business rule using the model it renders a new view and sends it to the user. Create an application using the MVC pattern is nothing more than to separate the logic in “packages” and make that information follow a certain path.

Information flow diagram of Spring Web MVC :


(1) A request from the user always arrives in a single servlet Dispatcher Servlet. This is a very common pattern in MVC frameworks called front controller (front controller) where a single servlet is responsible for receiving the request, delegate processing to other components of the application and return a response to the user.
(2) Once the Dispatcher servlet gets the request it must find out which controller the request will be sent. So it asks for help in the Handler Mapping. Based on the request URL Handler Mapping finds the controller.
(3) The request is then sent to the controller that will take care of the data contained therein. Once the controller receives the request it processes the data and performs some business rules of the application.
(4) Often rendered by the logic controller results in some information that should be taken back to the user (the model). Only sending information back is not enough, it must be formatted in a way that the user can understand, for that controller send it to the view. For this model and the view are encapsulated in a ModelAndView object and returned to the Dispatcher.
(5) As the controller is not stuck to just one view it sends a hint in the ModelAndView object to the Dispatcher to know which view should send the data. The Dispatcher passes this hint to viewResolver that returns the view which should be called.
(6) Finally, the Dispatcher sends the information (model) to the view (JSP page) who has just discovered. The page renders the information received and is returned to the user.
Here the original version: Original Version