Home » Posts tagged 'Java Collection API'

Tag Archives: Java Collection API


Java Collection API -Part 2 (Map)

In continuation of first part of introduction to Java Collection API Part 1, now we would be covering the other part and that is Map api. MAP is designed to store Key-Value pair combination as we know. Some distinct features of MAP are

  • Key can not be repeated
  • Key can be mapped to only one value
  • It depicts mathematical function F(x) -> y , where x represents key and y is the value
  • Basic operations provided by map : get, put , containsKey, containsValue , empty , size
  • Map provides collections views to iterate over the values it holds
    • ketSet      : Set of keys
    • value        : Collection os values, it is not a set as multiple keys can point to same values
    • entrySet  : Map internally contains the set of key-value pair which is represented my inner interface Map.Entry
  • These collections views are good for iteration , modification , removal but CAN NOT BE USED For ADDITION
  • Java API has provided three implementation of MAP interface: HashMap, HashTable, LinkedHashMap
  • MAP also has another sub interface SortedMap which is implemented  by TreeMap


1: HashMap: HashMap is most basic implementation of MAP interface

2: HashTable : Similar to HashMap
-Thread safe and synchronized

3: LinkedHashMap : Values are placed internally as likened list

4: TreeSet : Values are placed in sorted manner. Natural sort of Comparable/Comparator logic is used. It is the similar collection as TreeSet but here Key’s are compared and sorted while putting values in MAP.


Java Collection API -Part 1 (Set , List, Queue)

Java has defined main interface Collection from where all collection APIs are inherited. MAP is another interface which is also another very imported interface which I have covered in my another post Java Collection API Part-2

Collection Interface is subclasses into three another Interfaces:  Set, List and Queue. hierarchy is displayed in below image:


Collection interface provides abstract of following basic operations

  • add(E element)
  • addAll(Collection c)
  • contains(Object e)
  • size()
  • isEmpty()
  • remove(Object o)

In addition to these basic set of operations Specialised collection APIs further add their unique behaviours. Lets see in detail.

1: SET (Interface)
Set Interface is subclass of collection and it is designed to hold Unique values as it is inspired from mathematical set.
-No duplicate values.
-Not indexed

Specialised Implementation of SET
1.1: HashSet class ==>Set, is the basic implantation of Set.
Set is basically good option when you want to count Unique values. Ex Set set = new HashSet(Collection c);

1.2: Linked HashSet class ==> Set is set implantation where internally it maintains linked list where inserted values are also preserved with their order of insertion.

1.3: SortedSet (I) ==> Set it is designed to keep items in sorted values

1.4 TreeSet class==> SortedSet, in sorted set elements are placed in ascending ordered. Elements object class has to define the comparison logic with comparable or comparator.

2: LIST (Interface)
List is an ORDERED collection and can contain DUPLICATE values.
-Duplicate Yes
-Indexed Yes

Some additional methods exposed from List
-add(int index, Object obj)
-set(int index, Object obj)
-addAll(int index, Collection c )  etc

Specialised Implementation of LIST
2.1 ArrayList class ==> List this is a basic implementation of list which dynamically grows its size. You can also specify its initial capacity at the time of creation also.

2.2 Vector class ==>List similar to arraylist but all method are synchronized.

2.3 Linked List class==> List , Dqueue, Cloneable, Serializable
in addition to list it provides all basic operation get, insert, remove from front and back both side. Its Doubly linked List

-addFirst(Object o)
-addLast(Object o)

3: Queue (Interface)
Queue is another direct sub interface of Collection which is designed to hold temporarily objects before they get processed. Queue has some additional methods for basic operation
Queue Interface Structure

Queue Interface Structure
Type of Operation Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

Some major Specialisation of Queue
3.1 DQueue (I) ==> Queue
DQueue is similar to queue but offers all basic operation’s like insert, remove, get from Front and rear both ends.
Front(First)-> [][][][][][] ->Rear(Last)
So operation for add and remove wold be like:
Add: addFisrt, addLast, offerFirst, offerLast
Delete: removeFirst, removeLast, poolFirst, poolLast

3.2 Blocking Queue (I) ==> Queue
Blocking is a Queue that additianaly supports operations that wait for queue to get emplty while adding values or will wait for queue to become non empty while fetching some values.

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable


3.3 PriorityQueue Class ==> Queue
Unbounded queue based on proprity heap, Elements are ordered on natuarl order or based on the Comparator provided in Queue constructor.

3.4 LinkedBlocking Queue Class ==> BlockingQueue, Serialisable ++
Optianally bounded queue based on linked nodes which follows FIFO pattern.


Some of the common good practices I am trying to post here, in case if you some other better practices I would be glad if you can share here by your comments.

  1. Use Iterator or Advance For loop: 

Consider below code

               for(Person p : pList){
			System.out.println("Person Name: " + p.name);

This is not the correct way of modifying the collection, this would give java.util.ConcurrentModificationException since you are trying to modify the collection while iterating over it. Safe way to modify the collection is by using Iterator. Please note even in case of Iterator also it can throw this exception if the collection is modified out side this iteration.