how to sort hashmap in java


import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class StringDemoExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put(“9”, “EE”);
map.put(“8”, “DD”);
map.put(“7”, “CC”);
map.put(“6”, “BB”);
map.put(“5”, “AA”);
map.put(“4”, “bb”);
map.put(“3”, “dd”);
map.put(“2”, “aa”);
map.put(“1”, “cc”);
System.out.println(“Unsort HashMap values are …”);
printMap(map);
System.out.println(“Sorted HashMap…”);
Map<string, string=””> map1 = new TreeMap<string, string=””>(map);
printMap(map1);
}
private static void printMap(Map<string, string=””> map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println(“Key : ” + entry.getKey() + ”   Value : “
+ entry.getValue());
}
}
}
OUTPUT:

Unsort HashMap values are …
Key : 3   Value :  dd
Key : 2   Value :  aa
Key : 1   Value :  cc
Key : 7   Value :  CC
Key : 6   Value :  BB
Key : 5   Value :  AA
Key : 4   Value :  bb
Key : 9   Value :  EE
Key : 8   Value :  DD
Sorted HashMap…
Key : 1   Value :  cc
Key : 2   Value :  aa
Key : 3   Value :  dd
Key : 4   Value :  bb
Key : 5   Value :  AA
Key : 6   Value :  BB
Key : 7   Value :  CC
Key : 8   Value :  DD
Key : 9   Value :  EE

reverse string in java


import java.util.Scanner;
public class StringReverse {
public static void main(String[] args) {
String original = “”;
String reverse = “”;
Scanner in = new Scanner(System.in);
System.out.println(“Enter a string to reverse”);
original = in.nextLine();
int length = original.length();
for (int i = length – 1; i >= 0; i–)
reverse = reverse + original.charAt(i);
System.out.println(“Reverse string is: ” + reverse);
}
}

Date class in java? (Or) Date class in java.util package? (Or) Date class in java.sql package?


In java, Date class is present in the following two packages.

  1. java.util package

  2. java.sql package

Case study about Date class:

Example:

publicclass DateDemo1 {

     publicstaticvoid main(String[] args) {

          Date date = new Date ();

          System.out.println (date);

     }

}

Output:

F:\NAG\COREJAVA>javac DateDemo1.java

DateDemo1.java:6: cannot find symbol

symbol : class Date

location: class DateDemo1

               Date date = new Date();

               ^

DateDemo1.java:6: cannot find symbol

symbol : class Date

location: class DateDemo1

               Date date = new Date();

                               ^

2 errors

In the above example we will get compile time error.

To resolve this problem, we have two ways.

  1. By using import statement

  2. By using fully Qualified name

  1. By using import statement:

In this case we need the following import statement.

import java.util.Date;

         Or

import java.sql.Date;

Example1:

     By using java.util package

import java.util.Date;

publicclass DateDemo1 {

     publicstaticvoid main(String[] args) {

          Date date = new Date ();

          System.out.println (date);

     }

}

Output:

F:\NAG\COREJAVA>javac DateDemo1.java

F:\NAG\COREJAVA>java DateDemo1

Tue Apr 29 20:16:03 IST 2014

Example2:

   By using java.sql package

import java.sql.Date;

publicclass DateDemo1 {

     publicstaticvoid main(String[] args) {

          Date date = new Date(0);

          System.out.println (date);

     }

}

F:\NAG\COREJAVA>javac DateDemo1.java

F:\NAG\COREJAVA>java DateDemo1

1970-01-01

  1. By using fully Qualified name

Example1:

publicclass DateDemo1 {

     publicstaticvoid main(String[] args) {

          java.util.Date date = new java.util.Date();

          System.out.println (date);

     }

}

Output:

F:\NAG\COREJAVA>javac DateDemo1.java

F:\NAG\COREJAVA>java DateDemo1

Tue Apr 29 20:39:52 IST 2014

Example:

publicclass DateDemo1 {

     publicstaticvoid main (String [] args) {

          java.sql.Date date = new java.sql.Date (0);

          System.out.println (date);

     }

}

Output:

F:\NAG\COREJAVA>javac DateDemo1.java

F:\NAG\COREJAVA>java DateDemo1

1970-01-01

About java.util.Date:

Date class is direct child class of Object class.

Date class implements Serializable, Cloneable, Comparable interfaces.

Date class direct known subclasses are Date, Time, and Timestamp

Syntax:

public class Date

extends Object

implements Serializable, Cloneable, Comparable

Date class represents a specific instant in time, with millisecond precision.

From JDK 1.1 on words, the Date class had two additional functions.

It allowed the interpretation of dates as year, month, day, hour, minute, and second values.

It also allowed the formatting and parsing of date strings.

Unfortunately, the API for these functions was not amenable to internationalization.

As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings.

The corresponding methods in Date are deprecated.

Date class introduced in JDK1.0.

About java.sql.Date:

Date class is child class of java.util.Date class.

java.lang.Object

         java.util.Date

                 java.sql.Date

Date class implemented interfaces are Serializable, Cloneable, Comparable

Syntax:

public class Date

extends Date

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value

A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

To conform to the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

Explain about StringBuffer class ?


StringBuffer class is final class.
StringBuffer class is direct chaild class of Object class.
StringBuffer class implements Serializable, CharSequence.
StringBuffer class is mutable.
StringBuffer class is thread-safe.
StringBuffer class methods are synchronized.
StringBuffer class introduced in JDK1.0

 

Handler mappings


1.  BeanNameUrlHandlerMapping

2.  SimpleUrlHandlerMapping

3.  ControllerClassNameHandlerMapping

4.  CommansPathMapHandlerMapping

5.  DefaultAnnotationHandlerMapping

6.  RequestMappingHandlerMapping

7. AbstractControllerUrlHandlerMapping

8. AbstractDetectingUrlHandlerMapping

9. AbstractHandlerMapping

10. AbstractHandlerMethodMapping

11. AbstractUrlHandlerMapping

12. ControllerBeanNameHandlerMapping

13. RequestMappingInfoHandlerMapping

 

ArrayList in java example using iterator


import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIterator {
    public static void main(String args[]) {

        ArrayList al = new ArrayList();
        al.add(“Santosh”);
        al.add(“Nag”);
        al.add(“Rajesh”);
        al.add(“Santosh”);
        Iterator it = al.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Object Class


java.lang
Class Object

java.lang.Object

  *public class Object:

  • Class Object is the root of the class hierarchy.

  • Every class has Object as a superclass.

Version:

JDK1.0

*Methods of Oject Class:

           Object Class consists of following 11 methods

1. public boolean equals(Object obj)

    Indicates whether some other object is “equal to” this one.

  2. public int hashCode()

    Returns a hash code value for the object

  3. protected Object clone()        Throws CloneNotSupportedException

Creates and returns a copy of this object.

  4. public String toString()

   Returns a string representation of the object

   5. public final Class getClass()

     Returns the runtime class of this Object.

   6. protected void finalize()throws  Throwable

             Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

7. public final void wait()

                throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object

  8. public final void wait(long timeout)

                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

  9. public final void wait(long timeout)

                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

 10.public final void notify()

    Wakes up a single thread that is waiting on this object’s monitor.

  11. public final void notifyAll()

    Wakes up all threads that are waiting on this object’s monitor.

 

 

Explain about Java.util.ArrayList class?


java.util
Class ArrayList<E>

java.lang.Object

  java.util.AbstractCollection<E>

      java.util.AbstractList<E>

          java.util.ArrayList<E>

 All Implemented Interfaces:

 Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

public class ArrayList<E>

 extends AbstractList<E>

 implements List<E>, RandomAccess, Cloneable, Serializable

 Version:

   1.2

======================================================

Constructors of java.util.ArrayList class:

   1.ArrayList l = new ArrayList();

 Creates an empty ArrayList Object with default initial capacity is 10.

    Once ArrayList reaches its Max. Capacity then new ArrayList Object will be created with

      New Capacity = currentCapacity*(3/2)+1

     2. ArrayList l = new ArrayList( int initialcapacity);

                Creates an empty ArrayList Object with the specified initial capacity.

    3.ArrayList l = new ArrayList( Collection c);

                 Creates an equivalent ArrayList Object for the given Collection Object.

This constructor meant for interconversion between the Collection Object.

======================================================

Methods of java.util.ArrayList class :

    1.public int indexOf(Object o)

    2.public boolean addAll(Collection c)

     Throws:NullPointerException

    3.public void trimToSize()

   4. public void ensureCapacity(int    minCapacity)

  5.public int size()

  6.public boolean isEmpty()

  7.public boolean contains(Object o)

  8.public int lastIndexOf(Object o)

  9.public Object clone()

  10. public boolean add(E e)

  11.public void add(int index, E element)

     Throws:IndexOutOfBoundsException

  12. public Object[] toArray()

   13. public boolean remove(Object o)

  14.public void clear()

 15.public boolean addAll(int index, Collection c)

Throws:IndexOutOfBoundsExceptionNullPointerException

 16. public E remove(int index)

      Throws:IndexOutOfBoundsException

  17. public E get(int index)

      Throws:IndexOutOfBoundsException

 18. protected void removeRange(int fromIndex, int toIndex)

          Throws:IndexOutOfBoundsException

   19. public E set(int index, E element)

            Throws:IndexOutOfBoundsException

  20. public T[] toArray(T[] a)

 Throws:ArrayStoreExceptionNullPointerException

 ==================================

 Description of java.util.ArrayList class :

1.   ArrayList Object is dynamically resizable.

2.   ArrayList Object maintains the duplicate elements.

3.   ArrayList Object maintains in the list Insertion order.

4.   ArrayList Object also accepts the heterogeneous elements.

5.   ArrayList Object also maintains the elements based on index.

6.   ArrayList Object accepts null pointer constant any number of times.

Advantages:

      1. ArrayList Objects are Serializable Objects why because ArrayList       implements Serializable interface.

      2. ArrayList Objects are Cloneable Objects why because ArrayList       implements Cloneable interface.

     3. ArrayList also implements RandomAccess interface for frequent retrieval operations.

Disadvantages:

    1. ArrayList is not best suitable for frequent insertion and deletion operations as it requires internally lot of shifting operations.

 Example:

//ArraylistDemo.java

import java.util.*;

public class ArraylistDemo{

 public static void main(String[] args){

ArrayList l = new ArrayList();

                  l.add(“A”);

                  l.add(10);

                  l.add(“A”);

                  l.add(null);

        System.out.println(l);

                  l.remove(2);

        System.out.println(l);

                  l.add(2,“M”);

                  l.add(“N”);

      System.out.println(l);

}//main

}//class

javac ArrayListDemo.java

java ArraylistDemo

OUTPUT:

[A,10,A,null]

[A,10,null]

[A,10,M,null]

[A,10,M,null,N]

NOTE: Here toString() method provides like [].

       ArrayList and Vector Classes implements RandomAccess interface so that we can access any random element with same speed.