Home  >  Blog  >   Java

Java Collection Tutorial

In this article, you'll learn the various Java collections framework interfaces. Here, you will gain an understanding of collections and how they can improve both your work and your programs. Know the fundamentals of the Java Collections framework, including its implementations, operations, and algorithms. This Java collections tutorial will teach you everything you need about collections by getting you through simple, easy, step-by-step examples with working code. We've included as much helpful code as possible to demonstrate each concept in this Java tutorial.

Rating: 4.9
  
 
1244
  1. Share:
Java Articles

When selecting a data storage solution suitable for your requirements, you can choose from various options available today. There is something available for everyone, whether they are interested in in-memory coaching, non-relational databases, document stores, or key-value stores.

The Java collections framework offers a collection of interfaces and classes used to implement various algorithmic and data structures. A data structure in Java, known as a collection, stores a collection of data items connected in some way.

Table of Contents: Java Collection Tutorial

Some factors about the Java collection framework

  • The Java library includes many standard collection classes that can be used in various situations. Knowing how to select the appropriate collection and when to use it is integral to becoming a skilled Java programmer.
  • The most challenging part of the java programming language is collections. It also contains some of the most potent java language features, as is often the case.
  • Not only that, but by eliminating the hassles of manually writing operations, the Java framework enables programmers to solve more significant problems with ease.

What is Java collection?

A Java collection is a predefined architecture that can act like an object or group while storing a collection of elements.

One of the foundational elements of the Java programming language is the Java Collections Framework. Almost all programming languages make use of collections. Many programming languages, including Set, List, Stack, Queue, Etc., support different collections.

If you would like to enrich your career and become a professional in Java Collections, then enroll in: the “Core Java Training”  Course. This course will help you to achieve excellence in this domain.

What is the Java Collection Framework?

The Java collection framework gives programmers access to prepackaged data structures and manipulation algorithms. Java Collection offers Java Collection the ability to represent a collection of elements in classes and interfaces.

The collections framework was made with some goals in mind, including

  1. The framework had to work very well. The implementations of the primary collections (linked lists, dynamic arrays, hash tables, and trees) were to be very fast.
  2. The framework had to make it possible for different collections to work similarly and with a high level of compatibility.
  3. The framework had to make adding or changing a collection easy.

Java's Collection framework offers an architecture for storing and managing a collection of objects. All data operations, including insertion, sorting, searching, manipulation, and deletion, are possible with Java Collections. A collection in Java is a group of related objects. The Java Collection Framework offers numerous classes (List, Queue, Set, and Deque) and interfaces (Vector, ArrayList, PriorityQueue, LinkedList, LinkedHashSet, HashSet, and TreeSet).

With the help of the Java Collection Framework, users can store data, search for it, organize it, and add, remove, or update data on a collection of elements. Before moving on to the Java Collections Framework, you must learn and comprehend the Java Collections Hierarchy and its various descendants, classes, and interfaces.

MindMajix Youtube Channel

Types of Java Framework Collections 

A Java collection framework offers an architecture that can be utilized to both store and manipulate collections of objects. Java collection framework has the following components:

  • Interfaces
  • Classes
  • Algorithm

Let's learn about them in detail

Interfaces: The abstract data types are referred to as interfaces in Java. They allow Java collections to be manipulated in a way that is not tied to the specifics of their representation. The Set represents the sorted collection of elements. In addition, object-oriented programming languages form a hierarchy.

Classes: Java's classes make up the language's implementation of the collection interface. Reusable data structures are those that are employed repeatedly.

Algorithm: Algorithms are procedures for processing data in collections, including actions like searching and sorting. Algorithms are polymorphic because the same method can perform various implementations of the Java collection interface.

Related Article: Classes and Objects in Java

What are the different methods of the Java Collection?

The Collection interface has many methods that can be used to manipulate objects in various ways. All of its subinterfaces include these methods. There are fifteen different ways to manipulate collection elements in the Collection interface. These are what they are:

  •  add(): 

To insert a new item into a collection, call this method. Typically, the add() method will have the following syntax:

Syntax: 

add(Object element): boolean


If the element is added to the collection, it will return true; if it is already present and the collection forbids duplicates, it will return false.

  • addAll(): 

Adding or inserting an element into the collection is done using this method. The add() method's general syntax is as follows:

Syntax: 

addAll(Collection c): boolean

  • clear(): 

The collection's elements are all cleared or eliminated using this technique. This method's general format is as follows:

Syntax: 

clear(): void

Nothing is returned from this process.

  • contains(): 

The function tests the collection for the existence of a given element. It is the method by which an ingredient is sought. The following is a high-level explanation of the contains() function:

Syntax: 

contains(Object element): boolean

In other words, this method will return true if the given element is present and false otherwise.

  • containsAll(): 

This method determines whether or not a specified collection of elements is present. If all specified elements are present in the calling collection, it returns true; otherwise, it returns false. The following general syntax is used:

Syntax: 

containsAll(Collection c): boolean

  • equals(): 

It looks to see if one thing is the same as another. The basic structure goes like this:

Syntax: 

equals(Object element): boolean

  • hashCode(): 

It gives you the collection's hash code as an answer. It returns an integer value. This strategy can be stated generally as follows:

Syntax: 

hashCode(): int

  • isEmpty(): 

If a collection is empty, then it returns true. In other words, if the collection doesn't contain elements, this method returns true.

Syntax: 

isEmpty(): boolean

  • iterator(): 

An iterator is what it gives back. The basic structure is as follows:

Syntax: 

iterator(): Iterator

  • remove(): 

It takes out the selected item from the group. The basic syntax is shown below:

Syntax: 

remove(Object element): boolean

If the element was successfully deleted, then this method will return true. If not, it will give a false result.

  • removeAll(): 

All elements in the collection are removed using the removeAll() method. It returns true if all elements have been removed and false otherwise.

Syntax: 

removeAll(Collection c): boolean

  • retainAll(): 

The collection elements other than the ones you specify will be purged using this method. If all elements are deleted, it returns true; otherwise, it returns false.

Syntax: 

retainAll(Collection c): boolean

  • size(): 

The size() function calculates and returns the collection's full size. It returns an integer value. The basic syntax is shown below:

Syntax: 

size(): int

  • toArray(): 

It generates an array containing the collection's elements and returns them. Elements of the collection have been duplicated in the array.

Syntax: 

toArray(): Object[]

  • Object[ ] toArray(): 

Returns an array containing every element found in the collection being invoked. The collection elements are duplicated in the array elements.

Syntax: 

toArray(Object array[]): Object[]

Related Article: Java Tutorial

Hierarchy of Collection Framework in Java

The Java Collection Hierarchy contains the four core collections, interfaces, map, set, and list and is the hierarchy of the entire collection framework. There are also two additional specialized sorting interfaces, SortedSet and SortedMap. The Java.util.package contained all of the interfaces and classes for the collection hierarchy framework.

The Collection interface, the root interface for all collections in the API, is the virtual interface of the collections framework (Application programming interface).
In Java, it is positioned at the top of the collection hierarchy. It offers the fundamental functions for including and deleting elements from the collection.

The collection framework is, as we all know, a collection of classes and interfaces. Let's examine their hierarchy now.

The Java Collection Hierarchy classes provide dependable features and implement the core interfaces. Let's check out these methods.

Collection 

  • The entire root hierarchy is the Collection Interface. It offers all of the methods that every collection class supports.
  • The Collection interface expands the Iterable interface. There is only one method called iterator in the iterable interface (). The iterator method's purpose is to return the iterator object. We can iterate through the collection's elements using this iterator object.
  • Three components in Queue, List and Set extend the Collection interface. The Collection interface does not inherit from a map.

List 

  • An ordered list is used to represent the collections of elements. The list allows us to access the elements by index and search for specific elements.
  • This interface depicts a group of elements that are arranged in sequential order.
  • The fact that a list maintains the order of its elements means that both the order in which elements are added and the sequence we receive when retrieving elements are preserved.
  • At any point, we can add elements to the list. In Java, the list allows for the storage of duplicate elements.
  • Three actual subclasses of the list interface are ArrayList, Vector, and LinkedList.

Set 

  • The set interface is implemented by the classes LinkedHashSet, HashSet, and TreeSet, and the sorted interface extends the set interface.
  • The Set represents the sorted collection of elements.
  • This interface groups various elements, each of which is particular. It is used to store an assortment of distinctive elements.
  • When storing or retrieving elements, the set interface does not preserve any order, so the order in which we put the elements may not be preserved. A set's components can be arranged in any order.
  • The Set prohibits any duplicate elements.

Map 

  • A set of keys, a set of values, and a set of key-value mapping strategies are all made available by the Map interface. Key-value storage is made possible.
  • The collection interface does not inherit from the map interface. It represents an object that keeps and retrieves data in =Key/Value pairs, where a Key identifies an element's location within a Map.
  • Map stores key-value pairs using a hashing method.
  • Duplicate keys cannot be stored, but duplicate values are permitted.
  • Classes implementing the Map interface include LinkedHashMap, HashTable, HashMap, and TreeMap.

Stack 

  • Elements in stack data structures that can be advanced using the Last-In-First-Out (LIFO) algorithm are represented by this notation.
  • This user interface stands in for a Map whose data is ordered intuitively.
  • The TreeMap classes extend the Map interface and provide its implementation.

Queue 

  • A queue data structure holds an element until a user thread processes it. The queue provides the inspection, insertion, and extraction operations.
  • A queue is an ordered collection of homogeneous elements where items are removed from one end and added to the other end (front). Similar to a line at a store or in a supermarket.
  • This interface represents a unique class of list, where only the head's elements are removed.
  • The concrete subclasses of the queue interface are Priority queue, LinkedList, Priority Blocking Queue, ArrayQueue, and Linked Blocking Queue.

Deque

  • A double-ended queue can insert and remove elements at both ends. The stack class was preferred for this interface.
  • A sub-interface of the queue interface is called a deque (double-ended queue). Typically, it is pronounced "deck."
  • This interface is part of the collection framework introduced in Java SE 6.
  • The queue interface is extended by the deque interface, which implements deque using its method. The figure below depicts the hierarchy of the deque interface.
  • It is a linear collection of elements that allows for adding and removing elements at either end. In other words, it allows for both the insertion and removal of data from an object of a class that implements it.
  • The Deque interface is implemented by the LinkedList and ArrayDeque classes.
Related Article: Java Collections Interview Questions

Java Collections Classes

The Java Collections framework includes many different classes that implement the various interfaces that are part of the framework. ArrayList, HashMap, and HashSet are the most widely used implementations. Commonly, Collection classes have a fail-fast iterator and are not thread-safe. 

Common types of Java collection classes will be covered here.

  • Java HashSet Class
  • Java TreeSet Class
  • Java ArrayList Class
  • Java LinkedList Class
  • Java HashMap Class
  • Java TreeMap Class
  • Java PriorityQueue Class

1.Java HashSet Class

HashSet is the simplest implementation of the Set interface that a HashMap supports in Java. It allows for the null element and makes no guarantees about the Set's iteration order. 

Assuming the hash function distributes the elements among the buckets, this class provides constant time performance for basic operations (add, remove, contain, and size). We have control over the default capacity and load factor for this Set. The load factor determines how full the hash map can get before increasing its capacity mechanically.

Consider the following example code:

Output:

Vijay
Ravi
Ajay

2.Java TreeSet Class

TreeMap as a navigable set implementation. A set's elements can be ordered either by the constructor's default method of determining a logical order for the Set's components or by a Comparator supplied when the Set is created. In this implementation, the base operations are guaranteed to incur a log(n)-time cost (add, remove, and contain).

Sets that correctly implement the Set interface ensure that the ordering it maintains is consistent with equals, regardless of whether or not an explicit comparator is provided. For a more formal definition of "consistent with equals," see Comparable or Comparator. Two elements deemed equal by the TreeSet's compareTo (or compare) method are considered equal from the Set's perspective. A TreeSet instance compares elements using the compareTo (or compare) method, whereas the Set interface is defined as the equals operation.

Consider the following example:

Output:

Ajay
Ravi
Vijay

3.Java ArrayList Class

The List interface in Java is implemented as an adaptable array type called ArrayList. Supports all operations on optional lists and allows for any number of elements, including null. This class implements the List interface and has methods to adjust the underlying array's size that stores the list. 

Consider the following example code:

Output:

Ravi
Vijay
Ravi
Ajay

4.Java LinkedList Class

The LinkedList class implements the Collection interface in Java. Elements are stored in a doubly linked list on the inside. The overlapping information can be saved. It's not synchronized, but it remembers the order of inserts. Faster operations are possible in LinkedList because no shifting is required during the manipulation.

Consider the following example:

Output: 

Ravi
Vijay
Ravi
Ajay

5.Java HashMap Class

Implementation of the Map interface using hash tables. This implementation supports null values and the null key and offers all optional map operations. The HashMap class is similar to the Hashtable class, except that it is unsynchronized and supports null. This class does not guarantee the order of the map.

The HashSet class implements a set Interface. It stands for the collection that stores data using hash tables. The components of the HashSet are stored using hashing. It has unique items in it.

Consider the following example:

Output:

Iterating Hashmap…

1 Mango
2 Apple
3 Banana
4 Grapes

6.Java TreeMap Class

An implementation of NavigableMap based on Red-Black trees. The map can be ordered according to the keys' natural order or by a Comparator supplied when the map is created. With this implementation, the costs for the containsKey, get, put, and remove operations are guaranteed to be logged (n) in time. The algorithms in Introduction to Algorithms by Cormen, Leiserson, and Rivest are adaptations of those in the book.

To correctly implement the Map interface, a TreeMap, like any other sorted map, must ensure that its internal ordering is consistent with equals, regardless of whether or not an explicit comparator is provided. It is because the equals operation is used to define the Map interface, while the compareTo (or compare) method of a sorted map is always used to make significant comparisons. Therefore, from the point of view of a sorted map, if two keys are considered equal by this method, they are considered equal. A sorted map's behavior is still well-defined even if its ordering causes a conflict with equals, as long as it is not expected to follow the usual conventions of the Map interface.

Consider the following example code:

Output:

100 Amit
101 Vijay
102 Ravi
103 Rahul

7.Java PriorityQueue Class

When using a queue, it's often desirable to have elements processed differently than the default FIFO order. To resolve this issue, we can use PriorityQueue, instantiating it with a Comparator implementation. 

PriorityQueue has no limits and does not accept null values. Please visit Java Priority Queue, where you can test its functionality with a sample program, for further information.

Consider the following example code:

Output:

head: Amit Sharma
head: Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Benefits of Java Collections

Here are some benefits that include Java collections are:

  • Time requirements have been drastically reduced thanks to the predefined Java Collections algorithm APIs. Without these APIs, even mundane tasks like sorting would have required significant time investment. Using a predefined application programming interface (API) has simplified and improved the usefulness of training.
  • Java Collections have dramatically reduced the number of lines of code and provided a dependable means of reusing that code.
  • Programming was made easier thanks to Java Collections' simplification. The most time-efficient and effective methods of programming are those that are the easiest to implement.

Uses of java collections

Some common uses of java collections include

  • Storing data in a specific order: Lists help store information in a predetermined order. A list of names, sorted alphabetically, could be kept in an Array List.
  • Accessing data quickly: Data storage that facilitates rapid retrieval can be achieved with the help of a map. Using a student's name as the key, a Hash Map could be used to track their class details.
  • Updating data quickly: An advantage of using a set to store information is that it is simple to modify the information. A Tree Set would be helpful to keep track of a list of names, for instance, and easily add or remove entries as necessary.
  • Keeping track of changes: Queues are useful for storing data in a way that makes it possible to detect and follow changes. The best part about Linked List is that anyone can use it to keep a list of names and continually add new names to the end of the list.

Summary

The developer uses the Java collections framework to access predefined data structures and associated algorithms. A collection is a particular object that can store references to other collections. All operations that can be carried out on a given collection are explicitly listed in its corresponding collection interface. 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Core Java TrainingMay 21 to Jun 05View Details
Core Java TrainingMay 25 to Jun 09View Details
Core Java TrainingMay 28 to Jun 12View Details
Core Java TrainingJun 01 to Jun 16View Details
Last updated: 04 Apr 2023
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read more
Recommended Courses

1 / 15