Collections in Java – Tutorial

Collections in Java are utilized in pretty much every application. Java Collections Framework is one of the center piece of Java programming language. Java Collections instructional exercise will clarify Java Collections Framework in detail.

Collections in Java

What is Java Collections Framework?

Collections resemble compartments that bunches various things in a solitary unit. For instance; a container of chocolates, rundown of names and so on. Accumulations are utilized nearly in each programming language and when Java arrived, it additionally accompanied couple of Collection classes; Vector, Stack, Hashtable, Array. Java 1.2 gave Collections Framework that is engineering to speak to and control Collections in java standardly. Java Collections Framework comprises of following parts:

  • Interfaces: Java Collections Framework interfaces gives the unique information type to speak to accumulation. java.util.Collection is the root interface of Collections Framework. It is on the highest point of Collections structure progressive system. It contains some essential strategies, for example, size(), iterator(), add(), remove(), clear() that each Collection class must actualize. Some other imperative interfaces are java.util.List, java.util.Set, java.util.Queue and java.util.Map. Guide is the main interface that doesn't acquires from Collection interface yet it's a piece of Collections system. Every one of the accumulations system interfaces are available in java.util package.
  • Implementation Classes: Collections in Java gives center usage classes to accumulations. We can utilize them to make diverse sorts of accumulations in java program. Some imperative gathering classes are ArrayList, LinkedList, HashMap, TreeMap, HashSet, TreeSet.These classes settle a large portion of our programming needs however in the event that we need some unique accumulation class, we can extend them to make our custom accumulation class.

    Java 1.5 thought of string safe accumulation classes that permitted to change Collections while emphasizing over it, some of them are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet. These classes are in java.util.concurrent bundle. All the gathering classes are available in java.util and java.util.concurrent package.

  • Algorithms: Algorithms are helpful techniques to give some basic functionalities, for instance looking, arranging and shuffling.

Below class chart demonstrates Collections Framework progression. For effortlessness I have included just ordinarily utilized interfaces and classes.

Benefits of Java Collections Framework

Java Collections system have following benefits:

  • Reduced Development Effort – It accompanies practically all normal kinds of accumulations and helpful techniques to emphasize and control the information. So we can focus more on business rationale as opposed to structuring our accumulation APIs.
  • Increased Quality – Using center gathering classes that are all around tried builds our program quality instead of utilizing any home created information structure.
  • Reusability and Interoperability
  • Reduce effort – to gain proficiency with any new API on the off chance that we use center gathering API classes.

Java Collections Interfaces

Java gathering interfaces are the establishment of the Java Collections Framework. Note that all the center accumulation interfaces are nonexclusive; for instance public interface Collection<E>. The <E> linguistic structure is for Generics and when we pronounce Collection, we should utilize it to determine the kind of Object it can contain. It helps in decreasing run-time blunders by sort checking the Objects at gather time.

To keep the quantity of center accumulation interfaces reasonable, the Java stage doesn't give separate interfaces to every variation of every gathering sort. In the event that an unsupported task is summoned, an accumulation usage tosses a UnsupportedOperationException.

Collection Interface

This is the foundation of the gathering progression. An accumulation speaks to a gathering of articles known as its components. The Java stage doesn't give any immediate usage of this interface.

The interface has techniques to disclose to you what number of components are in the accumulation (size, isEmpty), to check whether a given article is in the gathering (contains), to include and expel a component from the accumulation (add, remove), and to give an iterator over the accumulation (iterator).

Collection interface additionally gives mass activities techniques that chip away at whole accumulation – containsAll, addAll, removeAll, retainAll, clear.

The toArray strategies are given as an extension among accumulations and more seasoned APIs that expect clusters on input.

Iterator Interface

Iterator interface gives techniques to emphasize over any Collection. We can get iterator example from a Collection utilizing iterator strategy. Iterator replaces Enumeration in the Java Collections Framework. Iterators enable the guest to expel components from the basic gathering amid the cycle. Iterators in accumulation classes execute Iterator Design Pattern.

Set Interface

Set is a gathering that can't contain copy components. This interface models the numerical set reflection and is utilized to speak to sets, for example, the deck of cards.

The Java stage contains three universally useful Set executions: HashSet, TreeSet, and LinkedHashSet. Set interface doesn't enable irregular access to a component in the Collection. You can utilize iterator or foreach circle to navigate the components of a Set.

List Interface

List is an arranged accumulation and can contain copy components. You can get to any component from it's record. Rundown is increasingly similar to exhibit with dynamic length. Rundown is a standout amongst the most utilized Collection type. ArrayList and LinkedList are usage classes of List interface.

List interface gives helpful techniques to include a component at explicit record, expel/supplant component dependent on list and to get a sub-list utilizing index.


Rundown strList = new ArrayList<>(); 

//include at last 

strList.add(0, "0"); 

//include at indicated index 

strList.add(1, "1"); 


strList.set(1, "2"); 



Collections class give some valuable calculation to List – sort, shuffle, reverse, binarySearch etc.

Queue Interface

Queue is an accumulation used to hold various components preceding handling. Other than essential Collection tasks, a Queue gives extra addition, extraction, and assessment operations.

Queues ordinarily, yet don't really, request components in a FIFO (first-in, first-out) way. Among the special cases are need lines, which request components as per a provided comparator or the components' normal requesting. Whatever the requesting utilized, the leader of the line is the component that would be expelled by a call to evacuate or survey. In a FIFO line, every single new component are embedded at the tail of the queue.

Dequeue Interface

A direct gathering that underpins component inclusion and expulsion at the two closures. The name deque is another way to say "twofold finished line" and is generally articulated "deck". Most Deque executions place no fixed points of confinement on the quantity of components they may contain, yet this interface bolsters limit limited deques just as those with no fixed size limit.

This interface characterizes techniques to get to the components at the two closures of the deque. Techniques are given to embed, evacuate, and inspect the element.

Map Interface

Java Ma is an item that maps keys to values. A guide can't contain copy keys: Each key can guide to at most one value.

The Java stage contains three broadly useful Map executions: HashMap, TreeMap, and LinkedHashMap.

The fundamental activities of Map are put, get, containsKey, containsValue, size, and isEmpty.

ListIterator Interface

An iterator for records that enables the developer to navigate the rundown in either course, adjust the rundown amid cycle, and get the iterator's present position in the list.

A ListIterator has no present component; its cursor position dependably lies between the component that would be returned by a call to past() and the component that would be returned by a call to next().

SortedSet Interface

SortedSet is a Set that keeps up its components in climbing request. A few extra activities are given to exploit the requesting. Arranged sets are utilized for normally requested sets, for example, word records and enrollment rolls.

SortedMap Interface

Map that keeps up its mappings in climbing key request. This is the Map simple of SortedSet. Arranged maps are utilized for normally requested accumulations of key/esteem sets, for example, word references and phone directories.

Java Collections Classes

Java Collections structure accompanies numerous execution classes for the interfaces. Most normal executions are ArrayList, HashMap and HashSet. Java 1.5 included Concurrent executions; for instance ConcurrentHashMap and CopyOnWriteArrayList. Generally Collection classes are not string safe and their iterator is flop quick. In this area, we will find out about regularly utilized accumulation classes.

HashSet Class

>Java HashSet is the essential usage the Set interface that is sponsored by a HashMap. It makes no assurances for emphasis request of the set and allows the null element.

This class offers consistent time execution for fundamental activities (add, remove, contains and size), accepting the hash work scatters the components legitimately among the containers. We can set the underlying limit and burden factor for this gathering. The heap factor is a proportion of how full the hash map is permitted to get before its ability is consequently increased.

TreeSet Class

A NavigableSet execution dependent on a TreeMap. The components are requested utilizing their normal requesting, or by a Comparator gave at set creation time, contingent upon which constructor is used.

This usage gives ensured log(n) time cost for the essential activities (include, evacuate and contains).

Note that the requesting kept up by a set (regardless of whether an unequivocal comparator is given) must be steady with equivalents in the event that it is to accurately actualize the Set interface. (See Comparable or Comparator for an exact meaning of steady with equivalents.) This is so on the grounds that the Set interface is characterized as far as the equivalents activity, however a TreeSet occasion plays out all component correlations utilizing its compareTo (or look at) strategy, so two components that are regarded equivalent by this technique are, from the viewpoint of the set, equal.

ArrayList Class

Java ArrayList is the resizable-exhibit usage of the List interface. Actualizes all discretionary rundown activities, and allows all components, including invalid. Notwithstanding actualizing the List interface, this class gives strategies to control the measure of the cluster that is utilized inside to store the rundown. (This class is generally proportional to Vector, then again, actually it is unsynchronized.)

The measure, isEmpty, get, set, iterator, and listIterator tasks keep running in steady time. The include task keeps running in amortized steady time, that is, including n components requires O(n) time. The majority of alternate tasks keep running in straight time (generally). The consistent factor is low contrasted with that for the LinkedList implementation.

LinkedList Class

Doubly-connected rundown execution of the List and Deque interfaces. Executes all discretionary rundown activities, and allows all components (counting null).

All of the activities execute as could be normal for a doubly-connected rundown. Tasks that record into the rundown will navigate the rundown from the earliest starting point or the end, whichever is nearer to the predetermined index.

HashMap Class

Hash table based execution of the Map interface. This usage gives the majority of the discretionary guide tasks, and allows invalid qualities and the invalid key. HashMap class is generally proportional to Hashtable, then again, actually it is unsynchronized and grants invalid. This class makes no certifications for the request of the map.

This execution gives steady time execution to the fundamental tasks (get and put). It gives constructors to set beginning limit and burden factor for the collection.

TreeMap Class

A Red-Black tree based NavigableMap execution. The guide is arranged by the common requesting of its keys, or by a Comparator gave at guide creation time, contingent upon which constructor is used.

This usage gives ensured log(n) time cost for the containsKey, get, put and expel tasks. Calculations are adjustments of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Note that the requesting kept up by a tree map, similar to any arranged guide, and regardless of whether an unequivocal comparator is given, must be steady with equivalents if this arranged guide is to effectively actualize the Map interface. (See Comparable or Comparator for an exact meaning of steady with equivalents.) This is so in light of the fact that the Map interface is characterized as far as the equivalents activity, yet an arranged guide plays out every single key correlation utilizing its compareTo (or think about) technique, so two keys that are regarded equivalent by this strategy are, from the stance of the arranged guide, rise to. The conduct of an arranged guide is all around characterized regardless of whether its requesting is conflicting with equivalents; it just neglects to comply with the general contract of the Map interface.

PriorityQueue Class

Queue forms it's components in FIFO request yet now and again we need components to be prepared dependent on their need. We can utilize PriorityQueue for this situation and we have to give a Comparator usage while instantiation the PriorityQueue. PriorityQueue doesn't permit invalid qualities and it's unbounded. For more insights regarding this, it would be ideal if you head over to java Priority Queue where you can check it's utilization with an example program.

Collections class

This class comprises only of static strategies that work on or return accumulations. It contains polymorphic calculations that work on accumulations, "wrappers", which return another gathering upheld by a predetermined accumulation, and a couple of different chances and ends.

This class contains strategies for gathering system calculations, for example, parallel inquiry, arranging, rearranging, switch etc.

Synchronized Wrappers

The synchronization wrappers include programmed synchronization (string security) to a self-assertive accumulation. Every one of the six center gathering interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static industrial facility method.


public static Collection synchronizedCollection(Collection c); 

public static Set synchronizedSet(Set s); 

public static List synchronizedList(List list); 

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m); 

public static SortedSet synchronizedSortedSet(SortedSet s); 

public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m); 

Each of these techniques restores a synchronized (string safe) Collection supported up by the predefined collection.

Thread Safe Collections

Java 1.5 Concurrent bundle (java.util.concurrent) contains string safe accumulation classes that enable accumulations to be changed while repeating. By structure iterator is flop quick and tosses ConcurrentModificationException. A portion of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Collections API Algorithms

Java Collections Framework gives calculation executions that are generally utilized, for example, arranging and seeking. Accumulations class contain these technique usage. The greater part of these calculations deal with List however some of them are pertinent for a wide range of collections.


The sort calculation reorders a List with the goal that its components are in climbing request as per a requesting relationship. Two types of the activity are given. The basic structure takes a List and sorts it as indicated by its components' characteristic requesting. The second type of sort takes a Comparator notwithstanding a List and sorts the components with the Comparator.


The mix calculation annihilates any hint of request that may have been available in a List. That is, this calculation reorders the List dependent on contribution from a wellspring of irregularity to such an extent that every single imaginable stage happen with equivalent probability, accepting a reasonable wellspring of haphazardness. This calculation is helpful in executing rounds of chance.


The binarySearch calculation looks for a predefined component in an arranged List. This calculation has two structures. The principal takes a List and a component to look for (the "seek key"). This structure accept that the List is arranged in rising request as per the characteristic requesting of its components. The second structure takes a Comparator notwithstanding the List and the pursuit key, and accept that the List is arranged into rising request as indicated by the predetermined Comparator. The sort calculation can be utilized to sort the List preceding calling binarySearch.


The recurrence and disjoint calculations test some part of the structure of at least one Collections.

  • frequency: checks the occasions the predefined component happens in the predetermined collection
  • disjoint: decides if two Collections are disjoint; that is, regardless of whether they contain no components in common

Min and Max values

The min and the maximum calculations return, separately, the base and greatest component contained in a predetermined Collection. Both of these tasks come in two structures. The straightforward structure takes just a Collection and returns the base (or most extreme) component as per the components' normal ordering.
The second structure takes a Comparator notwithstanding the Collection and returns the base (or greatest) component as indicated by the predefined Comparator.

Collection classes in a Nutshell

Collection Ordering Random Access Key-Value Duplicate Elements Null Element Thread Safety
ArrayList Yes Yes No Yes Yes No
LinkedList Yes No No Yes Yes No
HashSet No No No No Yes No
TreeSet Yes No No No No No
HashMap No Yes Yes No Yes No
TreeMap Yes Yes Yes No No No
Vector Yes Yes No Yes Yes Yes
Hashtable No Yes Yes No No Yes
Properties No Yes Yes No No Yes
Stack Yes No No Yes Yes Yes
CopyOnWriteArrayList Yes Yes No Yes Yes Yes
ConcurrentHashMap No Yes Yes No No Yes
CopyOnWriteArraySet No No No No Yes Yes

journaldev is optimized for learning.© journaldev .
All Right Reserved and you agree to have read and accepted our term and condition