Collection in Java in a Easy and Sorted way

  • By
  • July 23, 2019
  • JAVA ProgrammingSoftware Development
Collection in Java in a Easy and Sorted way

Collection in Java in an Easy and Sorted way

If you want to represent a group of the individual object as a single entity then Java Course In Puneshould go for Collection.

Difference b/w Collection and Array


  • These are Fixed in size.
  • Memory wise arrays are not recommended.
  • High performance.
  • Can hold only homogeneous data type.
  • No underline data structure is used so readymade methods are not available.
  • The array can be used to hold primitive data types and objects both.


  • These are Growable in nature.
  • Memory wise collection are recommended.
  • Low performance.
  • Can hold only homogenous and heterogeneous data type.
  • Implementation of every collection class is based on standard data structure i.e. ready made method available. And reduces complexity of program.
  • It can be used to hold only objects both.

Collection is a group of Individual objects represented as single entity. Common Methods Available in Collection are:

  1. boolean add(Object o)
  2. boolean addAll(Collectio o)
  3. boolean remove(Object o)
  4. boolean removeall(Collection c)
  5. boolean retain(Collection c) //To all except data in c
  6. void clear()
  7. boolean contains(Collection c)
  8. boolean containsAll(Collection c)
  9. Boolean isEmpty()
  10. int size()
  11. Object[] toArray()
  12. Iterator iterator()

# To provide support for data transfer every collection class by default implements serializable and Clonable interface

For Free Demo classes Call: 8237077325

Registration Link:Click Here!

1 List

The list is child interface(I) of the collection I.

  • I if you want to represent a group of the individual object as a single entity, where duplicates are allowed and insertion order must be preserved, then Java Training In Pune should go for the list.
  • Duplicates objects are identified based on the index. So index will play imp. role in the list.


List Interface defines the following methods:

  1. Void add(int index, Object o)
  2. Boolean addall(int index,Collection c)
  3. Object get(int index)
  4. Object remove(int index)
  5. Object set(int index, Object new)
  6. Int indexof(Object obj)
  7. Int LastIndexOf(Object o)
  8. ListIterator listIterator()



  • Underline data structure for arraylist is resizable/growable array.
  • Duplicates are allowed.
  • Insertion Order is preserved .
  • Heterogeneous objects are allowed, null insertion is possible.
  • Formulae for new capacity= (size*(3/2))+1
  • Types of constructor :
    • ArrayList l=new ArrrayList();
    • ArrayList l=new ArrrayList(int intial_capacity);
    • ArrayList l=new ArrrayList(Collection c);
  • ArrayList implement RandomAccess(for searching mainly) interface

1.2> LinkedList

  • The underline data structure is DLL.
  • Insertion order is preserved.
  • Duplicates are allowed.
  • Heterogeneous Objects are allowed.
  • Null insertion is allowed.
  • LinkedList is the best choice if the frequent operation is insertion or deletion in the middle.
  • And worst for retrieval operation.
  • Types of Constructor:
    • LinkedList l=new LinkedList();
    • LinkedList l=new LinkedList(Collection c);
  • Methods in LinkedList are:add(Object o);
  1. addFirst(Object o);
  2. addLast(Object o);
  3. add(index, Object);
  4. getFirst();
  5. getLast();
  6. get(int index);
  7. removeFirst();
  8. removeLast();

1.3> Vector

  • Underline data structure for vector is resizable/growable array.
  • Duplicates are allowed.
  • Insertion Order is preserved.
  • Heterogeneous objects are allowed, null insertion is possible.
  • Implements Serializable, clonnable and RandomAccess.
  • Note
    • Every method in Vector is Synchronized i.e. thread-safe.
    • All methods from ArrayList And LinkedList are non.synchronized,but we can have synchronize version of List by using Static SychronizedList() , from Collections class.Eg:

ArrayList l= new ArrayList()

List l1=Collections. SychronizedList(l)

  • Public static List SychronizedList(List l)
  • Types of Constructor:o           Vector v=new Vector(); //Creates empty vector object with default capacity 10 Once reaches max capacity then new Object is created with new capacity
    • New capacity= current*2
    • Vector v=new Vector(int capacity);
    • Vector v=new Vector(int initialCapacity,int incrementalCapacity);
    • Vector v=new Vector(Collection c);
    • Methods in Vector are:
      • To add:

    -add(Object o); //Collection§       add(int index,Object o); // List§       addElement(Object o); //Vector

    • To Remove:

    -remove(Object o);         //Colleection§       remove(int index);        //List§       removeElement(Object o); //Vector§       clear();//Collection§       removeAllElements();//Vector

    • To get Object:

    -v.get(int index); //List
    v.elementAt(int index); //Vector
    v.firstElement(); //Vector
    v.lastElement(); //Vector

    • Other Methods:
      • Int size()
      • Int capacity();
      • Enumeration elements();

For Free Demo classes Call: 8237077325

Registration Link:Click Here!

1.3.1> Stack   

  • It is a specially designed class for LIFO.
  • Types of Consstructor:
    • Stack sk = new Stack();
  • Methods:
    • Object push(Object o);
    • Object pop(Object o);
    • Object peek() //returns top of stack without removal
    • Boolean empty
    • int search(Object o);
      • //returns offset of the element, if element is not present then returns -1
Index 3 2 1 0
Stack A(top) B C D
Offset 1 2 3 4



  1. Three Cursors of java are:
    1. Enumeration //Interface
    2. Iterator
    3. ListIterator
  2. Enumeration:
    1. We can use enumeration by initialzing with elements() method available with vector class
    2. Enumeration e= v.elements();
    3. Methods available with enumeration:
      1. Public boolean hasMoreElements()
      2. Public Object nextElement()


  • Set is the child I of Collection.
  • If we want to represent group individual
  • Where duplicates are not allowed and insertion order is not preserved.

2.1 HashSet

  • Underline data structure is hashtable duplicate objects not allowed.
  • Insertion order not preserved.
  • It is based on the hashcode of the object.
  • Heterogeneous objects are allowed.
  • Implements a Serializable and Clonable interface.
  • Java Classes In Pune cannot guess the output as an insertion order is based on hashcode.
  • Types of Constructor:
    • HashSet h =new HashSet();//Initial capacity is 16
      // and default fill ratio is 0.75
      // It is also non as load factor
      // new capcity= 2*old capacity
    • HashSet h =new HashSet(int initialCapacity);
    • HashSet h =new HashSet(int initialCapacity, float fillRatio);
    • HashSet h =new HashSet(Collection c);

For Free Demo classes Call: 8237077325

Registration Link:Click Here!

2.2 LinkedHashSet

  • Duplicates are not allowed.
  • Insertion order is preserved.

2.3 SortedSet (I)

  • Can be implemented in trees.

2.4  NavigableSet

  • Methods available :

-Object o=s.floor(Object e);//Returns highest element which
// is <= to e.
o           Object o=s.lower(Object e);//return highest element<eo           Object o=s.ceiling(Object e);//returns lowest element >=eo           Object o=s.higher(Object e);//returns lowest element >eo           Object o=s.pollFirst();//return and remove first elemento           Object o=s.pollLast();//return and remove first element

2.4 TreeSet

  • Underline data structure is balanced tree
  • Duplicate objects not allowed.
  • Insertion order not preserved
  • Heterogeneous objects not allowed.
  • Types of constructor:

oTreeSet t=new TreeSet();

oTreeSet t=new TreeSet(Comparator c);

oTreeSet t=new TreeSet(Collection c);

oTreeSet t=new TreeSet(SortedSet s);

2.5 Comparable (I)

  • Present in lang package
  • Contains only one method. It returns positive if Object1 has to come after Object 2.


2.6 Comparator (I)·

  • If we are not satisfied with default sorting order, then we can go for customized sorting using a comparator.
  • It is present in java. util package.·
  • Methods
  • Public int compare(Object o1, Object o2)
  • Public Boolean equals(Object o)


Map is not child I of collection.

If you want to represent a group of objects as a key-value pair, then we should go for a map.

For eg:

  • StudentId will be key and student Name will be value
  • Both keys and value will be objects only.
  • Duplication of the key is not allowed.
  • But value can be duplicated.·
  • Each key-value pair is called as an entry
  • Hence map is considered a collection of the entry object
  • Map specific methods:
  • Object put(Object key, Object value);
  • Returns null normally, return old value if the key is duplicated.
  • Void put all(Map m);
  • Object get(key);
  • Object remove(key);
  • Boolean contains key(key);
  • Boolean containsValue(value);
  • Boolean isempty();
  • Int size();
  • Set keySet();
  • Set of all the keys
  • Collection values();
  • Set entrySet();//set of all the key and value·
  • Entry Interface :A map is group of key value pairs, each key value pair is called as entry.
  • Entry is inner I of the map,  i.e. without the existence of map object i.e. no chance of existence of entry object.

o           interface map{

interface Entry {
Object getkey();
Object getValue();
Object setValue(Object newObj);

3.1 HashMap·

  • Underline data structuire is HashTable.
  • Insertion order is not preserved.
  • It is based on HashCode of keys.
  • Duplicates key is not allowed but values can be duplicated.
  • Types of Constructor:


HashMap h =new HashMap();

//Initial capacity is 16
// and default fill ratio is 0.75
// It is also non as load factor
// new capcity= 2*old capacity

o HashMap h =new HashMap(int initialCapacity);

o HashMap h =new HashMap(int initialCapacity, float fillRatio);

o HashMap h =new HashMap(Map m);

3.2 LinkedHashMap·

  • Underline data structure is linked list + Hashtable
  • Insertion order is preserved
  • Introduced in 1.4v
  • Used in cache based apps
  • Types of Constructor:LinkedHashMap h =new HashMap();

//Initial capacity is 16
// and default fill ratio is 0.75
// It is also non as load factor
// new capcity= 2*old capacity

  • LinkedHashMap h =new HashMap(int initialCapacity);
  • LinkedHashMap h =new HashMap(int initialCapacity, float fillRatio);
  • LinkedHashMap h =new HashMap(Map m);

For Free Demo classes Call: 8237077325

Registration Link:Click Here!

3.3 IdentityHashMap·

  • It is exactly same as HashMap including methods and constructor.
  • In case of normal HashMap, JVM uses equals method to identify duplicate keys which are meant for contained comparison but, in case of identityHashMap JVM will use ==  to identity duplicate key which is for reference comparison.

3.4 WeakHashMap

  • Exactly the same as HashMap except following differences
  • In the case of HashMap even though object doesn’t have any reffrence, it is not eligible for gc(),if it is associated with HashMap.
  • In case of WeakHashMap if object doesn’t contain any reference it is eligible for garbage collection i.e. gc(); dominates WeakHashMap.

3.5 SortedMap·

  • It is a child I of Map.
  • If we want to represent key value pairs according to some sorting order of keys then we should go for sorted map.
  • Methods:
  1. s.firstKey();
  2. s.lastKey();
  3. s.headMap(Object key);
  4. s.tailMap(Object key);
  5. s.subMap(key1 , key2);
  6. Comparator c= s.comparator();

3.6 TreeMap

  • Underline data structure is a RED-BLACK tree.
  • Insertion order is not preserved.
  • Based on sorting order of keys.·
  • Duplicate keys are not allowed but value are allowed.
  • Hetergeneous objects are not allowed for keys.
  • Null insertion is not allowed.
  • Types of constructor:
  1. TreeMap t =new TreeMap();
  2. TreeMap t=new TreeMap(Comparator c);
  3. TreeMap t=new TreeMap(Map m);
  4. TreeMap t=new TreeMap(SortedMap m);

3.7 Hashtable·

Underline data structure for Hashtable is hashtable.

Duplicate keys are not allowed and values can be duplicated.·

Heterogeneous objects are allowed for both keys and values.

Null is not allowed for both key and value.

Every method present in hashtable is synchronized

Hence Hashtable objects are Thread Safe

It is the best if the frequent operation is retrieval operation.·

Types of constructor:

Hashtable t =new Hashtable();

//Creates empty hashtable with default capacity 11
// and default fill ratio 0.75

  • Hashtable t= new Hashtable(int initialcapacity);
  • Hashtable t= new Hashtable(int initialcapacity,int fillratio);
  • Hashtable t= new Hashtable(Map m);

For Free Demo classes Call: 8237077325

Registration Link:Click Here!

3.8 Properties·

In our program if anything which changes frequently like username, password, mobile no. etc are not recommended to hardcore in java program because

If there is any change to reflect that change recompilation, rebuild and redeployment of the app is required even sometimes server restart is required.

This creates big business impact to the client.

We can overcome this by using a properties file.

Constructor :

Properties p= new Properties();·


String getProperties(“PName”);

String s =p.setProperty(“Pname”,“PValue”);

Enumeration e= p.propertyNames();


4 Queue·

  • Child I of Collection.
  • Prior to processing if you want to represent a group of an object then we will go for queue.·
  • From 1.5v onwards, LinkedList class implement queue.
  • Methods:
  • Boolean offer( Object o): To add objects in the queue.
  • Object poll(): Used to remove and return head element of the queue.
  • Object remove(): Used to remove and return the head element of the queue.
  • If the queue is empty poll will return null, and remove will get runtime Exception saying NoSuchElementPresent.
  • Object peek() :  return head element of queue.
  • Object element() : return to head element of queue.
  • If the queue is empty peek will return null and element will give runtime Exception saying NoSuchElementAvailable ( confirm pls ).

4.1 PriorityQueue·

  • Dublicates are not allowed.·
  • Insertion order is not preserved, all element will be inserted based on some priority
  • Types of Constructor:
  • PriorityQueue p=new PriorityQueue();
  • PriorityQueue p=new PriorityQueue(int initialcapacity);
  • PriorityQueue p=new PriorityQueue(int initialcapacity, Comparator c);
  • PriorityQueue p=new PriorityQueue(SortedSet s);
  • PriorityQueue p=new PriorityQueue(Collections c);


# Collections (class)·


Collections c=new Collections();
Collections.sort(List l);
Collections.sort(List l, Comparator c);·


For Free, Demo classes Call: 8237077325

Registration Link: Click Here!

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *