Collections in Java - Beginners Guide
Whether you are a techie or not, you might be familiar with Java, a programming language that includes immense codes to develop web applications and software. But isn’t it difficult for Developers to learn large amounts of code to achieve such complex tasks? No, it is not; the Collections in Java can make this happen through a framework that offers an architecture for storing and managing a collection of objects.
It is the reason that Java was the sixth most widely used programming language in 2022, according to Statista. Thus, it is an extra bonus if you want to work with Java, as Java Collections reduces programming efforts.
But how do collections make Java stand out from the crowd? Read the blog to understand further the Java Collections Framework and its various Interfaces and Classes.
Table of Contents
1) An introduction to Java Collections
2) What is the Java Collections Framework?
3) Hierarchy of Collections Framework
4) What are the methods of Java Collections Interface?
5) Everything about Java Collections Interfaces
6) Everything about Java Collections Classes
7) Conclusion
An introduction to Java Collections
Java Collections is a fundamental part of the Java programming language. Simply put, it is a pre-structured framework to store and manipulate a group of objects, freeing up the user to concentrate on the important parts of the program rather than on the low-level plumbing.
The Collection is a one-stop solution that can perform all kinds of operations on data, ranging from searching, storing, inserting, manipulation and deletion. Thus, it becomes a single unit of objects that provides numerous Classes.
Before moving forward to the topic, first, let’s understand what Collection Interface and Classes are.
Collection Classes
These are user-defined blueprints or prototypes to create objects. It is used exclusively with static methods (provided by Interfaces) that operate on or return Collections common to all Objects.
Collection Interface
It is the core Interface implemented by all the Classes in the Collections Framework. However, it is implemented indirectly through various sub-types, such as List, Deque, etc. It provides a method for every Collection, thus building a basis for the Collections Framework.
What is the Java Collections Framework?
Before directly jumping onto the details of Java Collections, it is equally important to understand its framework first.
Before the Collections Framework (JDK 1.2), the standard mediums to group Java elements were Arrays, Vectors or Hashtables. However, these collections did not have a shared interface. Thus, although the primary objective of all the Collections was the same and independent, it was difficult for users to remember all the methods, syntaxes and constructors in every Class.
However, the Java Collections Framework provides a ready-made architecture to unify a group of elements or objects in the form of Classes. It allows the user to operate various data alteration operations like searching, storing, sorting, adding, deleting and updating data on a group of objects.
Hierarchy of Collections Framework
The Java utility package or Java.util comprises all the Classes and Interfaces for the Collections Framework. Let’s understand its hierarchy in detail:
On the surface of it, Collections Interface is at the root of the Collections Framework that contains an Interface named Iterable Interface. This Interface allows the iterator to rehearse through all the collections.
Further, all the Collections expand to this Collection Interface, as a result extending the characteristics of the iterator and all methods of this Interface. The following diagram will help you better understand the hierarchy of the Collection Framework:
What are the methods of Java Collections Interface?
The Java Interface comprises certain methods that all Collections can directly use to perform basic operations such as adding, removing, updating, altering and sorting Objects or elements. The following is the list of Methods of Java Collections Interface:
Methods |
Description |
add(E element) |
Adds a specific element to the Collection |
addAll(Collection collection) |
Adds all the elements of a specific Collection to the Collection |
clear() |
Removes all elements from the Collection |
contains(Object object) |
Returns true if the Collection contains the specified element |
containsAll(Collection collection) |
Returns true if the Collection contains all of the elements in the specified Collection |
equals(Object object) |
Compares the specified object with the other elements in the Collection for equality |
hashCode() |
Returns the hash code value for the Collection |
is Empty() |
Returns true if the Collection contains no elements |
iterator() |
Returns an iterator over the elements in the Collection |
max() |
Returns the maximum value present in the Collection |
remove(Object object) |
Removes the specified element from the Collection |
removeAll(Collection collection) |
Removes all of the elements in the specified Collection from the Collection |
retainAll(Collection collection) |
Preserves only the elements in the Collection that the specified Collection contains |
size() |
Returns the number of elements in the Collection |
toArray() |
Returns an array containing all of the elements in the Collection |
toArray(T[] array) |
Returns an array containing all of the elements in the Collection, using the specified array if it is large enough |
stream() |
Returns a serialised stream within the Collection (as its source) |
Here’s an example of how to use Collection Interface methods to manage a list of strings:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsExample
{
public static void main(String[] args)
{
// Create a new ArrayList of Strings
List
// Add some strings to the list
stringList.add("apple");
stringList.add("banana");
stringList.add("cherry");
// Print out the list
System.out.println("Original list: " + stringList);
// Sort the list using Collections.sort
Collections.sort(stringList);
// Print out the sorted list
System.out.println("Sorted list: " + stringList);
// Reverse the list using Collections.reverse
Collections.reverse(stringList);
// Print out the reversed list
System.out.println("Reversed list: " + stringList);
}
}
In this example, first, a new ArrayList of Strings is created, and some strings are added to it. Then, the Collections.sort method is used to sort the list alphabetically and print the sorted list. Further, the Collections.reverse Method is used to reverse the order of the list and print out the reversed list.
The output is as follows:
Original list: [apple, banana, cherry]
Sorted list: [apple, banana, cherry]
Reversed list: [cherry, banana, apple]
Everything about Java Collections Interfaces
Java Collections Interface makes the foundation of the Collections Framework. It extends to multiple Interfaces where each Interface stores a specified data type. Let’s look at those Interfaces in detail:
List Interface
L The List is the child Interface of the Collection Interface, directly derived from the Java utility package. It is one of the most used Collection types that allows the user to maintain elements in an organised manner with the help of indexing methods such as inserting, deleting and sorting the elements. It also allows the user to duplicate the data present in it.
List Interface can be implemented by the Classes such as ArrayList, LinkedList, Vector and Stack. Here is an example of declaring List Interface:
import java.util.ArrayList;
import java.util.List;
public class Example
{
public static void main(String[] args)
{
// create a new ArrayList instance
List
// add elements to the list
myList.add("apple");
myList.add("banana");
myList.add("orange");
// print the contents of the list
System.out.println(myList);
// access an element by its index position
String fruit = myList.get(0);
System.out.println("The first fruit is " + fruit);
// remove an element from the list
myList.remove("banana");
// print the updated list
System.out.println(myList);
}
}
Output:
[apple, banana, orange]
The first fruit is apple
[apple, orange]
Set Interface
Unlike List Interface, the Set Interface does not contain duplicate elements. It styles the mathematical set abstraction and is used to represent sets. The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet.
Here is how to instantiate Set Interface:
import java.util.HashSet;
import java.util.Set;
public class SetExample
{
public static void main(String[] args)
{
// Create a new HashSet
Set
// Add some elements to the Set
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
// Print the size of the Set
System.out.println("Size of the Set: " + names.size());
// Check if an element is present in the Set
System.out.println("Is Bob present in the Set? " + names.contains("Bob"));
// Remove an element from the Set
names.remove("Charlie");
// Print all the elements of the Set using a for-each loop
for (String name : names)
{
System.out.println(name);
}
// Clear all the elements of the Set
names.clear();
// Check if the Set is empty
System.out.println("Is the Set empty? " + names.isEmpty());
}
}
The output is as follows:
Size of the Set: 4
Is Bob present in the Set? true
Bob
Alice
David
Is the Set empty? True
Understand the basics of JavaScript and learn how to implement JavaScript with HTML; register for our JavaScript For Beginners course now!
Queue Interface
The Queue Interface is a Linear Collection that allows data manipulation operations on the Collection’s elements. Also, it can hold numerous elements before processing them in an ordered manner. This Interface follows the FIFO (First In First Out) principle, i.e., it first processes the priority elements in a specified Collection. The various Classes which implement Queue Interface are PriorityQueue, Deque, ArrayDequeu, etc. It can be declared in the following manner:
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample
{
public static void main(String[] args)
{
// create a new queue
Queue
// add elements to the queue
queue.add("apple");
queue.add("banana");
queue.add("cherry");
// display the elements of the queue
System.out.println("Elements of the queue: " + queue);
// remove the head of the queue
String head = queue.remove();
System.out.println("Removed element: " + head);
// display the remaining elements of the queue
System.out.println("Elements of the queue: " + queue);
// check if the queue contains an element
boolean containsBanana = queue.contains("banana");
System.out.println("Does the queue contain banana? " + containsBanana);
// get the size of the queue
int size = queue.size();
System.out.println("Size of the queue: " + size);
}
}
The output is as follows:
Elements of the queue: [apple, banana, cherry]
Removed element: apple
Elements of the queue: [banana, cherry]
Does the queue contain banana? true
Size of the queue: 2
Map Interface
Map supports values based on keys, i.e., pairing keys and values for mapping data. Although this Interface allows the user to duplicate values in different keys, it doesn’t support duplicating the keys as they cannot have multiple mappings.
import java.util.*;
public class MapExample
{
public static void main(String[] args)
{
Map
// Add some key-value pairs to the map
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);
// Print out the values associated with each key
System.out.println("Alice's age: " + map.get("Alice"));
System.out.println("Bob's age: " + map.get("Bob"));
System.out.println("Charlie's age: " + map.get("Charlie"));
// Print out all the keys in the map
System.out.println("Keys: " + map.keySet());
// Print out all the values in the map
System.out.println("Values: " + map.values());
// Print out all the key-value pairs in the map
System.out.println("Entries: " + map.entrySet());
// Remove a key-value pair from the map
map.remove("Charlie");
// Print out the updated key-value pairs in the map
System.out.println("Entries (after removal): " + map.entrySet());
}
}
The output will be as follows:
Alice's age: 25
Bob's age: 30
Charlie's age: 35
Keys: [Bob, Alice, Charlie]
Values: [30, 25, 35]
Entries: [Bob=30, Alice=25, Charlie=35]
Entries (after removal): [Bob=30, Alice=25]
SortedSet Interface
SortedSet is an alternative to the Set Interface that maintains the elements in ascending order. This Interface provides additional operations to order the elements naturally. The following Java program is used for SortedSet Interface:
import java.util.SortedSet;
import java.util.TreeSet; ;
public class SortedSetExample
{
public static void main(String[] args)
{
// Create a SortedSet of Strings
SortedSet
// Add some elements to the set
set.add("banana");
set.add("apple");
set.add("cherry");
set.add("date");
// Print the sorted set
System.out.println("Sorted Set: " + set);
// Get the first element of the set
String first = set.first();
System.out.println("First Element: " + first);
// Get the last element of the set
String last = set.last();
System.out.println("Last Element: " + last);
// Get a view of the portion of the set between "banana" (inclusive) and "date" (exclusive)
SortedSet
System.out.println("Subset: " + subset);
// Get a view of the portion of the set starting from "cherry" (inclusive)
SortedSet
System.out.println("Tail Set: " + tailSet);
}
}
The output will be:
Sorted Set: [apple, banana, cherry, date]
First Element: apple
Last Element: date
Subset: [banana, cherry]
Tail Set: [cherry, date]
Deque Interface
Deque means double-ended Deque, which means that this Interface supports inserting and deleting elements from both ends of the Deque. It extends the Queue Interface and is implemented by the ArrayDeque class. Insert, Remove and Examination Methods are provided to access the elements in this Interface. The program will be:
import java.util.*;
public class DequeExample
{
public static void main(String[] args)
{
Deque
// Add elements to the front of the deque
deque.addFirst(1);
deque.addFirst(2);
deque.addFirst(3);
// Add elements to the back of the deque
deque.addLast(4);
deque.addLast(5);
deque.addLast(6);
// Print the elements in the deque
System.out.println("Elements in the deque: " + deque);
// Remove elements from the front of the deque
int first = deque.removeFirst();
System.out.println("Removed first element: " + first);
int second = deque.removeFirst();
System.out.println("Removed second element: " + second);
// Remove elements from the back of the deque
int last = deque.removeLast();
System.out.println("Removed last element: " + last);
int secondLast = deque.removeLast();
System.out.println("Removed second last element: " + secondLast);
// Print the remaining elements in the deque
System.out.println("Remaining elements in the deque: " + deque);
}
}
The output will be as follows:
Elements in the deque: [3, 2, 1, 4, 5, 6]
Removed first element: 3
Removed second element: 2
Removed last element: 6
Removed second last element: 5
Remaining elements in the deque: [1, 4]
Become a master at developing a web application using Java programming with our Web Development Using Java Training course now!
SortedMap Interface
Unlike a regular Map that sorts the elements haphazardly, the SortedMap Interface orders its elements so that those can be set across in ascending order of keys. Thus, this Interface provides a naturally ordered Collection of keys implemented by the TreeMap class. The program will be:
import java.util.*;
public class SortedMapExample
{
import java.util.*;
public static void main(String[] args)
{
SortedMap
// Add elements to the SortedMap
sm.put("Alice", 30);
sm.put("Bob", 25);
sm.put("Charlie", 35);
sm.put("David", 40);
sm.put("Eva", 27);
// Print the SortedMap
System.out.println("SortedMap: " + sm);
// Get the first key and value from the SortedMap
String firstKey = sm.firstKey();
int firstValue = sm.get(firstKey);
System.out.println("First key: " + firstKey);
System.out.println("First value: " + firstValue);
// Get the last key and value from the SortedMap
String lastKey = sm.lastKey();
int lastValue = sm.get(lastKey);
System.out.println("Last key: " + lastKey);
System.out.println("Last value: " + lastValue);
// Get the sub-Map from "Bob" to "Eva"
SortedMap
System.out.println("Sub-Map from Bob to Eva: " + subMap);
// Remove the element with key "David"
sm.remove("David");
System.out.println("SortedMap after removing David: " + sm);
// Clear the SortedMap
sm.clear();
System.out.println("SortedMap after clearing: " + sm);
}
}
The output it gives is:
SortedMap: {Alice=30, Bob=25, Charlie=35, David=40, Eva=27}
First key: Alice
First value: 30
Last key: Eva
Last value: 27
Sub-Map from Bob to Eva: {Bob=25, Charlie=35, David=40}
SortedMap after removing David: {Alice=30, Bob=25, Charlie=35, Eva=27}
SortedMap after clearing: {}
Everything about Java Collections Classes
Collections in Java implement Collections Interface through Classes. Classes are used with static Methods to return operations in Collections. While it inherits the Object Class, other common implementations are ArrayList, HashMap, etc. Let’s look at the commonly used Collections Classes:
HashSet Class
The HashSet Class implements the Set Interface and stores the elements using a Hashtable. The elements in this Class are inserted based on Hash codes rather than synchronised. Additionally, a HashSet allows null elements as well. Let’s have a look at a simple example of HashSet:
import java.util.HashSet;
public class HashSetExample
{
public static void main(String[] args)
{
// Create a new HashSet
HashSet
// Add some elements to the HashSet
myHashSet.add("Apple");
myHashSet.add("Banana");
myHashSet.add("Orange");
myHashSet.add("Grapes");
myHashSet.add("Apple"); // Adding duplicate element
// Print the HashSet
System.out.println("HashSet contains: " + myHashSet);
// Check if an element is present in the HashSet
String searchElement = "Grapes";
if (myHashSet.contains(searchElement))
{
System.out.println(searchElement + " is present in the HashSet");
} else { System.out.println(searchElement + " is not present in the HashSet");
}
// Remove an element from the HashSet
String removeElement = "Banana";
myHashSet.remove(removeElement);
System.out.println(removeElement + " removed from the HashSet");
// Print the updated HashSet
System.out.println("HashSet after removal: " + myHashSet);
// Clear the HashSet
myHashSet.clear();
System.out.println("HashSet after clear: " + myHashSet);
}
}
ArrayList Class
An ArrayList Class implements a List Interface. It is a resizable Array that allows storing of the List. This Class also allows null elements. Three different types of Arrays are as follows:
a) One-dimensional Array – Contains one row to arrange the elements in synchronised order of addresses.
b) Two-dimensional Array – Contains two rows and columns to arrange the elements in the form of a matrix.
c) Multidimensional Array – Multidimensional Array combines various two-dimensional Arrays.
An example of ArrayList Class can be as follows:
import java.util.ArrayList;
public class ArrayListExample
{
public static void main(String[] args)
{
// Create an ArrayList of integers
ArrayList
// Add some elements to the ArrayList
numbers.add(5);
numbers.add(10);
numbers.add(15);
// Print the elements of the ArrayList
for (int i = 0; i < numbers.size(); i++)
{
System.out.println(numbers.get(i));
}
// Remove an element from the ArrayList
numbers.remove(1);
// Print the updated elements of the ArrayList
for (int i = 0; i < numbers.size(); i++)
{
System.out.println(numbers.get(i));
}
}
}
The output will be:
5
10
15
5
15
LinkedList class
The LinkedList class implements both the List and Deque Interface, which uses a doubly Linked List to store the elements. This Class is similar to ArrayList Class. The elements inserted in a LinkedList are not synchronised; instead, they are stored in memory locations with a data value and address the part that looks something like this:
Following is an example of a LinkedList Class:
import java.util.LinkedList;
public class LinkedListExample
{
public static void main(String[] args)
{
// Create a new LinkedList
LinkedList
// Add some elements to the list
list.add("apple");
list.add("banana");
list.add("cherry");
// Print the list
System.out.println("LinkedList: " + list);
// Get the first element
String first = list.getFirst();
System.out.println("First element: " + first);
// Get the last element
String last = list.getLast();
System.out.println("Last element: " + last);
// Remove the first element
list.removeFirst();
System.out.println("After removing first element: " + list);
// Remove the last element
list.removeLast();
System.out.println("After removing last element: " + list);
// Add an element at the beginning of the list
list.addFirst("orange");
System.out.println("After adding element at the beginning: " + list);
// Add an element at the end of the list
list.addLast("grape");
System.out.println("After adding element at the end: " + list);
// Get the size of the list
int size = list.size();
System.out.println("Size of the list: " + size);
// Check if the list contains an element
boolean contains = list.contains("banana");
System.out.println("List contains 'banana': " + contains);
// Clear the list
list.clear();
System.out.println("After clearing the list: " + list);
}
}
The output will be as follows:
LinkedList: [apple, banana, cherry]
First element: apple
Last element: cherry
After removing first element: [banana, cherry]
After removing last element: [banana]
After adding element at the beginning: [orange, banana]
After adding element at the end: [orange, banana, grape]
Size of the list: 3
List contains 'banana': true
After clearing the list: []
HashMap Class
A HashMap implements the Map Interface. The data is stored in key-value pairs and accessible through another type of index, i.e., Integers. It also permits null values and null keys but not duplications. Additionally, this Class does not ensure any order of the map. The implementation of a HashMap looks like this:
import java.util.HashMap;
public class HashMapExample
{
public static void main(String[] args)
{
// Create a new HashMap
HashMap
// Add key-value pairs to the HashMap
map.put("John", 25);
map.put("Alice", 32);
map.put("Bob", 27);
map.put("Kate", 29);
// Get the value associated with a key
int age = map.get("Alice");
System.out.println("Alice's age is " + age);
// Check if a key is present in the HashMap
boolean isPresent = map.containsKey("Bob");
System.out.println("Is Bob present in the map? " + isPresent);
// Remove a key-value pair from the HashMap
map.remove("Kate");
// Iterate over the keys in the HashMap
for (String name : map.keySet())
{
System.out.println(name + " is " + map.get(name) + " years old");
}
}
}
Its output will be as follows:
Alice's age is 32
Is Bob present in the map? true
John is 25 years old
Alice is 32 years old
Bob is 27 years old
Learn about the primary concepts of Advanced Java with our Introduction To Java EE Training Course now!
TreeSet Class
The TreeSet Class implements the Set Interface that uses a tree-like structure to store elements. The elements are maintained in a set using their natural ordering or a comparator to order the Objects of Classes at the time of set creation.
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String[] args)
{
// create a new TreeSet of integers
TreeSet
// add some elements to the TreeSet
numbers.add(10);
numbers.add(5);
numbers.add(20);
numbers.add(15);
numbers.add(25);
// print the TreeSet
System.out.println("TreeSet: " + numbers);
// get the first element of the TreeSet
int first = numbers.first();
System.out.println("First element: " + first);
// get the last element of the TreeSet
int last = numbers.last();
System.out.println("Last element: " + last);
// remove an element from the TreeSet
numbers.remove(15);
System.out.println("TreeSet after removing 15: " + numbers);
}
}
Following will be the output:
TreeSet: [5, 10, 15, 20, 25]
First element: 5
Last element: 25
TreeSet after removing 15: [5, 10, 20, 25]
TreeMap class
It is a class used to implement a Map Interface where the map is sorted according to the natural order of its keys or by a comparator. TreeMap is one of the efficient ways to sort and store key-value pairs. However, the implementation is not sequential. It is because when multiple threads try to access a map, the map's structure is consequently modified. Additionally, it does not allow null or duplicate values in the Collection. The Java program of a TreeMap class will look like this:
import java.util.*;
public class TreeMapExample
{
public static void main(String[] args)
{
// create a TreeMap object
TreeMap
// put some key-value pairs in the TreeMap
treeMap.put("Alice", 25);
treeMap.put("Bob", 30);
treeMap.put("Charlie", 35);
treeMap.put("David", 40);
treeMap.put("Emily", 45);
// print the TreeMap
System.out.println("TreeMap: " + treeMap);
// get the value associated with a key
int age = treeMap.get("Charlie");
System.out.println("Charlie's age: " + age);
// remove a key-value pair
treeMap.remove("David");
// print the TreeMap again
System.out.println("TreeMap after removing David: " + treeMap);
}
}
The output will be as follows:
TreeMap: {Alice=25, Bob=30, Charlie=35, David=40, Emily=45}
Charlie's age: 35
TreeMap after removing David: {Alice=25, Bob=30, Charlie=35, Emily=45}
Conclusion
The Collections in Java is the backbone of the Java programming language. Its Interfaces and Classes allow Developers to effortlessly run programs across networks, systems, software and devices. We hope that with the information provided in the blog, you were able to learn about Java Collections in detail.
Learn how to develop an application using Java with our Java Swing Development Training course now!