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

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());
        }
    }
}

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.

 

Q) Difference between Hashtable and HashMap ?


Hashtable :

  1. All methods are synchronized.

  2. Hashtable is thread safe.

  3. Performance is poor.

  4. Null is not allowed for both key and value, otherwise NullPointerException.

  5. Introduced in 1.0 version and it is legacy.

HashMap :

  1. No method is synchronized.

  2. HashMap object is not thread safe.

  3. Performance is good.

  4. Null is allowed as both key and value.

  5. Introduced in 1.2 and not legacy.

Explain about LinkedList? Or Constuctors , methods of LinkedList ? Or Explain bout java.util.LinkedList with an example?


java.util
Class LinkedList<E>

java.lang.Object

java.util.AbstractCollection<E>

java.util.AbstractList<E>

java.util.AbstractSequentialList<E>

java.util.LinkedList<E>

All Implemented Interfaces:

Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>

 public class LinkedList<E>

 extends AbstractSequentialList<E>

implements List<E>, Deque<E>, Cloneable, Serializable

 Since:

1.2

Method OF LinkedList :

1.  boolean add(E e)

           Throws:

UnsupportedOperationException

ClassCastException

NullPointerException

IllegalArgumentException

IllegalStateException

2. boolean addAll(Collection c)

Throws:

UnsupportedOperationException

ClassCastException

NullPointerException

IllegalArgumentException

IllegalStateException

3. boolean remove(Object o)

Throws:

ClassCastException

NullPointerException

UnsupportedOperationException

4. boolean removeAll(Collection c)

Throws:

UnsupportedOperationException

ClassCastException

NullPointerException

5. void clear()

Throws:

UnsupportedOperationException

6. boolean contains(Object o)

Throws:

ClassCastException

NullPointerException

7. boolean containsAll(Collection c)

Throws:

ClassCastException

NullPointerException

8.  boolean retainAll(Collection c)

Throws:

UnsupportedOperationException

ClassCastException

NullPointerException

9.           int size()
10.       boolean isEmpty()

11.       Iterator<E> iterator()

12.       Object[] toArray()

13.       <T> T[] toArray(T[] a)

Throws:

ArrayStoreException

NullPointerException

14.       boolean equals(Object o)

15.       public int hashCode()

Constructors of LinkedList :

  1. LinkedList l = new LinkedList();

  2. LinkedList l = new LinkedList(Collectio c);

 About LinkedList :

  1. The underlying data structure is resizable Array or Growable Array.

  2. LinkedList object also maintains elements insertion order.

  3. LinkedList object also allows duplicate elements.

  4. Null insertion is possible.

  5. Heterogeneous objects are allowed.

  6. Implements Serializable and Cloneable interface but not RandomAcess.

Advantage of LinkedList :

           LinkedList is the best choice if our frequent operation is insertion or deletion in the middle.

Di – Advantage of LinkedList :

           LinkedList is worst choice if our frequent operation is Retrival operation.

Example of LinkedList :

 import java.util.*;

public class LinkedListDemo {

     public static void main(String[] args) {

          LinkedList l = new LinkedList();

          l.add(49);

          l.add(“Nag”);

          l.add(“Abhi”);

          l.add(null);

          l.add(“Abhi”);

          l.add(0, “durga”);

          l.set(0, “Softwatr”);

          l.add(“www.chennarapu.wordpress.com”);

          l.removeFirst();

          l.addFirst(“Raj”);

          l.getFirst();

          l.getLast();

          System.out.println(l);

     }

}

OutPut:

D:\NAG\COREJAVA>javac LinkedListDemo.java

Note: LinkedListDemo.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

D:\NAG\COREJAVA>java LinkedListDemo

[Raj, 49, Nag, Abhi, null, Abhi, http://www.chennarapu.wordpress.com]

Q)Comparison Between collections and Arrays?


Collections :

1) Collections are not fixed In size.
2) With respect to memory collections are good.
3) With respect to performance collections shows worst performance.
4) Collections can hold heterogeneous data elements.
5) Every Collection class has built by using some Data structure.
6) Collection can hold only Objects but not primitives.

Arrays:

1.)Arrays are fixed In size.
2) with respect to memory arrays are not good.
3) With respect to performance the arrays are recommended to use.
4) Arrays can only hold homogeneous data elements.
5) There is no underlying Data Structure.
6) Arrays can hold both Objects and primitives.

Explain about java.util NavigableSet Interface?


java.util 
Interface NavigableSet<E>

All Superinterfaces:

Collection<E>, Iterable<E>, Set<E>, SortedSet<E>

public interface NavigableSet<E>

extends SortedSet<E>

Since:

1.6

Methods of  NavigableSet interface :

1.E floor(E e)

Throws:

          ClassCastException 

          NullPointerException

2.E ceiling(E e)

Throws:

          ClassCastException 

          NullPointerException

3.E higher(E e)

Throws:

          ClassCastException 

          NullPointerException

4.E lower(E e)

Throws:

          ClassCastException 

          NullPointerException

5.E pollFirst()

6.E pollLast()

7.NavigableSet<E> headSet(E toElement,

                        boolean inclusive)

Throws:

           ClassCastException 

           NullPointerException 

           IllegalArgumentException

8.NavigableSet<E> tailSet(E fromElement,

                        boolean inclusive)

Throws:

           ClassCastException 

           NullPointerException 

           IllegalArgumentException

9.NavigableSet<E> subSet(E fromElement,

                       boolean fromInclusive,

                       E toElement,

                       boolean toInclusive)

Throws:

          ClassCastException 

          NullPointerException 

          IllegalArgumentException

10.NavigableSet<E> descendingSet()

11.SortedSet<E> headSet(E toElement)

Throws:

          ClassCastException 

          NullPointerException 

          IllegalArgumentException

12.SortedSet<E> tailSet(E fromElement)

Throws:

          ClassCastException 

          NullPointerException 

          IllegalArgumentException

13.SortedSet<E> subSet(E fromElement,

                    E toElement)

Throws:

          ClassCastException 

          NullPointerException 

          IllegalArgumentException

14.Iterator<E> descendingIterator()

15.Iterator<E> iterator()