ZOFTINO.COM android and web dev tutorials

Java Collections

Collections are containers of objects with functionality to add, remove, modify and aggregate objects. Java collections framework provides various collections such as the ones which allow duplicate element, the ones which store only unique elements, the ones which maintains order, etc.

The framework contains interfaces for different types of collection objects and implementations of the interfaces with various operations to perform search, sort, and insert etc.

Table of Contents

Why Collections

To store group of objects, you can use arrays. The problem with arrays is that when you declare it you need to specify the number of elements it is going to contain. It can’t grow or shrink. You can’t enforce complete type safety.

You may need to store data in different data structures which allow different operations to be performed efficiently. Collections use different data structures and provide efficient algorithms to perform operations.

Like any other java frameworks, collections provide commonly used functionality related to data structures and operations, so you don’t have to spend time and effort in creating them from scratch leading to increased speed and quality of programs.

Using generics, element type of collections can be declared as parameter leading to stronger type safty.

Collection Interfaces

Collections framework defines interfaces for different types of collections.

collections interface hierarchy

Collection

Collection interface declares methods for common functionality to add (add(), addAll()) and remove (remove()) elements, get collection size (size()), remove all elements (clear()), convert collection to array (toArray()), convert collections to stream (stream()) and to check if collection is empty or not (isEmpty()) and collection contains give object or not (contains()). There is no direct implementation of Collection interface.

Iterable

Collection interface extends Iterable interface which defines methods for traversing elements of collection (iterator() return iterator object) and executing an action for each element of collection (forEach() takes Consumer argument representing action to be called for each element). It also define spliterator() method which return Spliterator object which allow partitioning and traversing of elements of the collection and improves performance in multi threading context.

Set

Set extends Collection interface and contains non duplicate elements. It can contain only one null element. SortedSet, which extends Set, keeps the elements in natural order or based on the give comparator. It provides methods such as first(), last(), headset(), tailSet() and subset().

NavigableSet, which extends SortedSet, provides methods such as lower() (returns greatest element which is less than the given element), floor() (returns greatest element which is less than or equals to the given element), higher() (returns least element which is greater than the given element) and ceiling() (returns least element which is greater than or equals to the given element). It also provides methods to get view of reverser order of elements in the set (descendingSet()) and to retrieve and remove the first and last elements (pollFirst(), pollLast()). You can create a sub set using trailSet(), headSet() and subSet() methods.

For details and examples, please see Java set examples.

List

List can contain duplicate elements. It allows adding, removing and getting an element at a particular position in the list by specifying index. It can contain multiple null elements, if null is allowed. In addition to inherited methods from Collection interface, List defines methods for sorting element (sort()), getting sub list which contains elements between two indices (subList()), for finding index of a given element (indexOf()) and for iterating elements starting from the given index (listIterator()).

For details and examples, please see Java List examples.

Queue

Queue is used to hold elements which are processed one by one later. For adding an element to queue, add() and offer() methods are used. The difference between add() and offer() methods is that add() throws exception and offer() returns false if element being added can’t be added to the queue. Similarly, for removing head element of the queue, remove() and poll() methods are used, while remove() throws exception, poll() returns false if the queue is empty.

Queue provides element() and peek() methods to obtain head element without removing it from queue. Again, element() throws exception and peek() return null if queue is empty.

BlockingQueue interface extends Queue and provides additional functionality related to adding and removing elements by defining put() and take() methods. If capacity is full, adding an element using put() method blocks the operation until the space becomes available. Similarly, take() method blocks if queue is empty until the queue becomes non empty.

It also provides offer() and poll() methods with time out for blocking add and remove operations when queue is full or empty respectively. It defines drainTo() method which removes all the elements from queue and returns a collection containing all the element.

Depending on the queue implementation, the order of the elements can be first in first out (FIFO) or last in first out (LIFO) or the elements can be ordered using the given comparator. The order decides which elements is the head of the queue and will be the candidate for poll() and peek().

TransferQueue interface extends BlockingQueue. It provides transfer() method to block producer until consumer receives the element. Method tryTransfer() either transfer the element immediately to consumer if consumer is available or tries to transfer for certain time if consumer is not available.

For details and examples, please see Java Queue examples.

Dequeue

Dequeue is a double ended queue. Unlike Queue, elements can be added and removed at both head and tail ends. The interface declares methods for adding, removing and examining elements from both ends and all of them exist in two versions, one throws exception and other one returns false or null when operation fails.

For adding elements, addFirst(), addLast(), offerFirst() and offerLast() methods are provided. For removing elements, removeFirst(), removeLast(), pollFirst() and pollLast() methods are provided. For examining element, getFirst(), peekFirst(), getLast() and peekLast() methods are provided.

Dequeue can be used as last in first out stack using addFirst(), removeFirst() and getFirst() methods.

For details and examples, please see Java Deque examples.

Map

Map interface define methods to add key and value pairs. In map, keys are non duplicate and each key maps to a value. It provides put and putAll methods for adding key and values, remove method for removing key and value, replace method for replacing value for a given key, get method for getting value associated with the given key, keySet method returns set of keys, size method return size of map, values method returns collection of values and forEach method for performing given action for each element in the map.

SortedMap interface extends Map and it orders keys in natural order or by using the specified comparator. It provides methods such as firstKey(), lastKey(), headMap() ( returns view of portion of map with keys less than the given key), tailMap() (return view of portion of map with keys greater than the give key), subMap() (returns view of portion of map with keys in the specified range) and entrySet().

NavigableMap interface extends SortedMap. It provides methods such as ceilingEntry and ceilingKey() for respectively getting entry or key whose key is least among the keys which are greater than or equals to the given key, floorEntry() and floorKey() for getting entry or key whose key is greatest among the keys which are less than or equals to the given key, lowerKey and lowerEntry, higherKey and higherEntry, firstKey, lastKey, tailMap, headMap and subMap.

For details and examples, please see Java Map examples.