21
NovCollection Framework in Java
Java Collections Framework
In Java programming, organizing data is a basic task. But how can one efficiently manage large volumes of data? This is where the Java Collections Framework helps. With its strong array of classes and interfaces, manipulating data becomes easy.
In this Java Tutorial, we will examine the Java Collections Framework, including Java Collections Interface Methods and Java Collection Class.
Master full stack development with our Java Full Stack Developer Certification Training—learn from industry experts!
What is the Java Collection Framework?
- Imagine that you had a box that had many tools, one for each specific task.
- The Java collection framework is quite similar to such a box because it offers a common design for representing and manipulating collections.
- Simply put, collections are merely objects used to pack several items together in one container. This framework has a variety of interfaces (like List, Set, and Map) and their implementations (such as ArrayList, HashSet, and HashMap) that enable you to efficiently save, retrieve, and manipulate data.
Let’s Understand the Java Collection vs Collections Framework
You might come across two similar terms: "Collection" and "Collections Framework." They might seem similar but are very different from each other; let's try to understand the difference between them.
Collection | Collections Framework |
Collection is a root interface that defines basic operations for a group of objects. | A Collection Framework is a comprehensive architecture that includes interfaces, implementations, and algorithms to work with groups of objects. |
It includes List, Set, and Queue interfaces. | It includes interfaces like Collection, List, Set, Queue, and Map. |
It is used to represent a single unit of objects and provide standard methods to manipulate them. | It is used to provide a unified, flexible, and efficient way to manage collections of objects, along with utility methods for common operations like sorting and searching. |
Hierarchy of Collection Framework
Understanding the hierarchy of the Collections Framework is crucial. Think of it like a family tree where each branch represents a different interface or class. Here’s a simplified view:
Java Collections Interface Methods
Each interface in the Java Collections Framework defines a set of methods that can be used to manipulate the data. Some common methods include:
- add(E e)-Adds an element to the collection.
- remove(Object o)-Removes a specific element from the collection.
- size()-Returns the number of elements in the collection.
- clear()-Removes all elements from the collection.
- contains(Object o)-Checks if a specific element is present in the collection.
- isEmpty()-Checks if the collection is empty.
import java.util.ArrayList;
import java.util.List;
public class ListMethodsExample {
public static void main(String[] args) {
// Example of List methods
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println("Size: " + names.size());
names.remove("Bob");
System.out.println("Contains Bob? " + names.contains("Bob"));
names.clear();
System.out.println("Is empty? " + names.isEmpty());
}
}
Output
Size: 2
Contains Bob? false
Is empty? true
Java Collections Interface
The Java Collections Framework has various key interfaces. Some of them are as follows:
- List- An ordered collection (also known as a sequence). Lists can contain duplicate elements. Common implementations include ArrayList and LinkedList.
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(2); // Allows duplicates
System.out.println(numbers);
}
}
Output
[1, 2, 2]
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // Does not allow duplicates
System.out.println(uniqueNames);
}
}
Output
[Bob, Alice]
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Alice");
queue.add("Bob");
System.out.println(queue.poll()); // Retrieves and removes the head
System.out.println(queue);
}
}
Output
Alice
[Bob]
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Alice", 32); // Overwrites the previous value
System.out.println(ages);
}
}
Output
{Bob=25, Alice=32}
Java Collection Classes
For each interface, the Java Collections Framework provides concrete classes. These classes implement the interfaces and provide specific behaviors. Here are a few key classes:
- ArrayList: It is a resizable array implementation of the List interface.
- LinkedList- It is a doubly-linked list implementation of the List and Deque interfaces.
- HashSet: It is the hash table-based implementation of the Set interface.
- TreeSet: It is a NavigableSet implementation based on a TreeMap.
- HashMap: A hash table-based implementation of the Map interface.
- TreeMap-A Red-Black tree-based implementation of the NavigableMap interface.
When to Use Which Collection Framework?
Choosing the right collection class can be tricky. Here are some guidelines to help you decide:
- ArrayList: Use when you need fast random access to elements and don’t expect many insertions or deletions.
- LinkedList: Ideal for scenarios where you need fast insertions and deletions and can tolerate slower random access.
- HashSet: Perfect for when you need a collection with no duplicates and don’t care about the order of elements.
- TreeSet-Use when you need a sorted set, and you can tolerate slower performance than HashSet.
- HashMap-Great for quick lookups using keys when order doesn’t matter.
- TreeMap-This is best when you need a map that maintains a sorted order of its keys.
Collections API Algorithms
The Java Collections Framework also provides a set of algorithms that operate on collections, making tasks like sorting and searching straightforward. These algorithms are available through the Collections class, which includes:
- sort(List<T> list)-It sorts the elements of the list.
- binarySearch(List<? extends Comparable<? super T>> list, T key)-It searches for a key in a sorted list using the binary search algorithm.
- reverse(List<?> list)-It reverses the order of elements in the list.
- shuffle(List<?> list)-It randomly shuffles the elements in the list.
- min(Collection<? extends T> coll)-It returns the minimum element in the collection.
- max(Collection<? extends T> coll)-It returns the maximum element in the collection.