Java Collection Framework (JCF)
Java Collection Framework (JCF) is a set of classes and interfaces that
provide ready-made data structures to store and manipulate groups of
objects efficiently.
Java provides collection interfaces like List, Set, Map, and Queue,
with ready-made classes such as ArrayList, HashSet, HashMap, and
PriorityQueue, so you don’t have to write data-handling code from
scratch.
The Collection Framework improves productivity by making code
more reusable, maintainable and faster to develop.
Features of Java Collection Framework
Provides ready-to-use data structures (e.g., ArrayList, HashSet,
HashMap).9
Offers interfaces (Collection, List, Set, Map, Queue) to define
standard behaviors.
Supports dynamic resizing, unlike arrays with a fixed size.
Includes algorithms (sorting, searching, iteration) via the Collections
utility class.
Improves code reusability and performance by reducing boilerplate
code.
Core Interfaces of the Collection FrameWork
The foundation of the Collections Framework is built on interfaces like
Collection, List, Set, Queue, Deque and [Link] define the behavior of
different collection types and serve as a blueprint for implementations.
Collection Interface
List Interface
Set Interface
Queue Interface
Deque Interface
Map Interface
List Interface in Java
The List interface in Java extends the Collection interface and is part of
the [Link] package. It is used to store ordered collections where
duplicates are allowed and elements can be accessed by their index.
Maintains insertion order
Allows duplicate elements
Supports null elements (implementation dependent)
Supports bidirectional traversal using ListIterator
To use a List, we must instantiate a class that implements it.
Example classes that implement it are ArrayList and LinkedList
List<Type> list = new ArrayList<Type>();
Hierarchy of List Interface
It extends the Collection interface.
Example1
import [Link].*;
public class ListDemo {
public static void main(String[] args) {
// Creating List
List<String> list = new ArrayList<>();
//Adding Elements
[Link]("Linux");
[Link]("Microsoft");
[Link]("Unix");
[Link]("AppleOS");
[Link]("After Adding: " +
list);
// Add element at specific index
[Link](1, "Anroid");
[Link]("After Inserting at
index 1: " + list);
//Size of list
[Link]("Size of List: " +
[Link]());
// Iteration using for loop
[Link]("Using for loop:");
for(int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
//Update element
[Link](2, "Microsoft OS");
[Link]("After Updating
index 2: " + list);
//Remove element by index
[Link](3);
[Link]("After Removing
index 3: " + list);
//Remove element by value
[Link]("Linux");
[Link]("After Removing
'Apple': " + list);
//Searching element
[Link]("Contains Anroid
Os? " + [Link]("Anroid"));
//Using enhanced for loop
[Link]("Using enhanced for
loop:");
for(String oslist : list) {
[Link](oslist);
}
//Using Iterator
[Link]("Using Iterator:");
Iterator<String> it = [Link]();
while([Link]()) {
[Link]([Link]());
}
//Using ListIterator (forward +
backward)
[Link]("Using ListIterator
(Forward):");
ListIterator<String> lit =
[Link]();
while([Link]()) {
[Link]([Link]());
}
[Link]("Using ListIterator
(Backward):");
while([Link]()) {
[Link]([Link]());
}
// Sorting list
[Link](list);
[Link]("After Sorting: " +
list);
// Reversing list
[Link](list);
[Link]("After Reversing: "
+ list);
// Checking empty
[Link]("Is list empty? " +
[Link]());
//Clearing list
[Link]();
[Link]("After Clearing: "
+ list);
}
}
Example2
import [Link].*;
public class ListMenuDriven {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<Integer> list = new ArrayList<>();
int choice, element, index;
do {
[Link]("\n===== LIST MENU =====");
[Link]("1. Add Element");
[Link]("2. Insert Element at
Position");
[Link]("3. Remove Element by
Value");
[Link]("4. Remove Element by
Index");
[Link]("5. Display List");
[Link]("6. Search Element");
[Link]("7. Update Element");
[Link]("8. Size of List");
[Link]("9. Sort List");
[Link]("10. Clear List");
[Link]("11. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter element: ");
element = [Link]();
[Link](element);
[Link]("Element added.");
break;
case 2:
[Link]("Enter index: ");
index = [Link]();
[Link]("Enter element: ");
element = [Link]();
if (index >= 0 && index <= [Link]()) {
[Link](index, element);
[Link]("Element inserted.");
} else {
[Link]("Invalid index!");
}
break;
case 3:
[Link]("Enter element to remove: ");
element = [Link]();
if ([Link]([Link](element)))
[Link]("Element removed.");
else
[Link]("Element not found.");
break;
case 4:
[Link]("Enter index to remove: ");
index = [Link]();
if (index >= 0 && index < [Link]()) {
[Link](index);
[Link]("Element removed.");
} else {
[Link]("Invalid index!");
}
break;
case 5:
[Link]("List Elements: " + list);
break;
case 6:
[Link]("Enter element to search: ");
element = [Link]();
if ([Link](element))
[Link]("Element found.");
else
[Link]("Element not found.");
break;
case 7:
[Link]("Enter index to update: ");
index = [Link]();
if (index >= 0 && index < [Link]()) {
[Link]("Enter new value: ");
element = [Link]();
[Link](index, element);
[Link]("Element updated.");
} else {
[Link]("Invalid index!");
}
break;
case 8:
[Link]("Size of List: " +
[Link]());
break;
case 9:
[Link](list);
[Link]("List sorted.");
break;
case 10:
[Link]();
[Link]("List cleared.");
break;
case 11:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice!");
}
} while (choice != 11);
[Link]();
}
}
Set in Java
In Java, the Set interface is a part of the Java Collection
Framework, located in the [Link] package. It represents a
collection of unique elements, meaning it does not allow
duplicate values.
The set interface does not allow duplicate elements.
It can contain at most one null value except TreeSet
implementation which does not allow null.
The set interface provides efficient search, insertion, and
deletion operations.
Hierarchy of Set interface
Creating Set Objects
Set<String> set = new HashSet<>();
Classes that implement the Set interface
HashSet: A set that stores unique elements without any
specific order, using a hash table and allows one null element.
EnumSet : A high-performance set designed specifically for
enum types, where all elements must belong to the same
enum.
LinkedHashSet: A set that maintains the order of insertion
while storing unique elements.
TreeSet: A set that stores unique elements in sorted order,
either by natural ordering or a specified comparator.
Example
import [Link].*;
public class SetMenuProgram {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int choice;
String element;
do {
[Link]("\n--- Set Menu ---");
[Link]("1. Add Element");
[Link]("2. Remove Element");
[Link]("3. Display Set");
[Link]("4. Search Element");
[Link]("5. Size of Set");
[Link]("6. Clear Set");
[Link]("7. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // consume newline
switch(choice) {
case 1:
[Link]("Enter element to add: ");
element = [Link]();
if([Link](element))
[Link]("Element added
successfully.");
else
[Link]("Duplicate element! Not
added.");
break;
case 2:
[Link]("Enter element to remove: ");
element = [Link]();
if([Link](element))
[Link]("Element removed.");
else
[Link]("Element not found.");
break;
case 3:
[Link]("Set elements: " + set);
break;
case 4:
[Link]("Enter element to search: ");
element = [Link]();
if([Link](element))
[Link]("Element found.");
else
[Link]("Element not found.");
break;
case 5:
[Link]("Size of Set: " + [Link]());
break;
case 6:
[Link]();
[Link]("Set cleared.");
break;
case 7:
[Link]("Exiting program...");
break;
default:
[Link]("Invalid choice!");
}
} while(choice != 7);
[Link]();
}
}
ArrayList in Java
An ArrayList in Java is a resizable array implementation of
the List interface found in the [Link] package. Unlike standard
arrays which have a fixed size, an ArrayList can grow or shrink
dynamically as elements are added or removed.
Hierarchy of ArrayList
It implements List Interface which is a sub-interface of Collection
Interface.
import [Link].*;
public class ArrayListMenu {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<String> list = new ArrayList<>();
int choice, index;
String element;
do {
[Link]("\n===== ARRAYLIST MENU
=====");
[Link]("1. Add Element");
[Link]("2. Insert Element at
Index");
[Link]("3. Remove Element by
Value");
[Link]("4. Remove Element by
Index");
[Link]("5. Display List");
[Link]("6. Search Element");
[Link]("7. Update Element");
[Link]("8. Size of List");
[Link]("9. Sort List");
[Link]("10. Reverse List");
[Link]("11. Copy List");
[Link]("12. Clear List");
[Link]("13. Traverse using
Iterator");
[Link]("14. Traverse using
ListIterator (Forward)");
[Link]("15. Traverse using
ListIterator (Backward)");
[Link]("16. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // fix input issue
switch (choice) {
case 1:
[Link]("Enter element: ");
element = [Link]();
[Link](element);
[Link]("Element added.");
break;
case 2:
[Link]("Enter index: ");
index = [Link]();
[Link]();
[Link]("Enter element: ");
element = [Link]();
if (index >= 0 && index <= [Link]()) {
[Link](index, element);
[Link]("Element inserted.");
} else {
[Link]("Invalid index!");
}
break;
case 3:
[Link]("Enter element to remove: ");
element = [Link]();
if ([Link](element))
[Link]("Element removed.");
else
[Link]("Element not found.");
break;
case 4:
[Link]("Enter index to remove: ");
index = [Link]();
if (index >= 0 && index < [Link]()) {
[Link](index);
[Link]("Element removed.");
} else {
[Link]("Invalid index!");
}
break;
case 5:
[Link]("List: " + list);
break;
case 6:
[Link]("Enter element to search: ");
element = [Link]();
if ([Link](element))
[Link]("Element found.");
else
[Link]("Element not found.");
break;
case 7:
[Link]("Enter index to update: ");
index = [Link]();
[Link]();
if (index >= 0 && index < [Link]()) {
[Link]("Enter new value: ");
element = [Link]();
[Link](index, element);
[Link]("Element updated.");
} else {
[Link]("Invalid index!");
}
break;
case 8:
[Link]("Size: " + [Link]());
break;
case 9:
[Link](list);
[Link]("List sorted.");
break;
case 10:
[Link](list);
[Link]("List reversed.");
break;
case 11:
ArrayList<String> copy = new
ArrayList<>(list);
[Link]("Copied List: " + copy);
break;
case 12:
[Link]();
[Link]("List cleared.");
break;
case 13:
[Link]("Using Iterator:");
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]());
}
break;
case 14:
[Link]("Using ListIterator
(Forward):");
ListIterator<String> lit =
[Link]();
while ([Link]()) {
[Link]([Link]());
}
break;
case 15:
[Link]("Using ListIterator
(Backward):");
ListIterator<String> lit2 =
[Link]([Link]());
while ([Link]()) {
[Link]([Link]());
}
break;
case 16:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice!");
}
} while (choice != 16);
[Link]();
}
}
Java Program: Add, Remove Duplicates & Sort ArrayList
import [Link].*;
public class ArrayListDuplicateRemove {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> list = new
ArrayList<>();
// 1. Input elements
[Link]("Enter number of
elements: ");
int n = [Link]();
[Link]("Enter elements:");
for (int i = 0; i < n; i++) {
[Link]([Link]());
}
[Link]("Original List: " +
list);
// 2. Remove duplicates using
LinkedHashSet (keeps order)
Set<Integer> set = new
LinkedHashSet<>(list);
[Link]();
[Link](set);
[Link]("After Removing
Duplicates: " + list);
// 3. Sort the list
[Link](list);
[Link]("Sorted List: " +
list);
[Link]();
}
}
Java Program (Without Set): Remove Duplicates + Sort
import [Link].*;
public class ARemoveDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> list = new
ArrayList<>();
ArrayList<Integer> uniqueList = new
ArrayList<>();
// 1. Input elements
[Link]("Enter number of
elements: ");
int n = [Link]();
[Link]("Enter elements:");
for (int i = 0; i < n; i++) {
[Link]([Link]());
}
[Link]("Original List: " +
list);
// 2. Remove duplicates manually
for (int i = 0; i < [Link](); i++)
{
int element = [Link](i);
// check if element already exists
in uniqueList
if ()
{
[Link](element);
}
}
[Link]("After Removing
Duplicates: " + uniqueList);
// 3. Sort the list
[Link](uniqueList);
[Link]("Sorted List: " +
uniqueList);
[Link]();
}
}
Write a method removeEvenLength that takes an ArrayList of Strings as
a parameter and that removes all of the strings of even length from the
list.
PROGRAM:
import [Link];
class ArrayListData
{
public static void removeEvenLength(ArrayList<String> array) {
for (int i = 0; i < [Link](); i++) {
String word = [Link](i);
if ([Link]() % 2 == 0) {
[Link](i);
i--;
}
}
}
}
public class RemoveList
{
public static void main(String[] args)
{
// create an empty array list with an initial capacity
ArrayList<String> arrlist = new ArrayList<String>(5);
// use add() method to add elements in the list
[Link]("Java");
[Link]("C++");
[Link]("DataScience");
[Link]("Python");
[Link]("Cyber");
[Link]("<====ArrayList Item====>");
for (String str : arrlist)
{
[Link](str);
}
[Link](arrlist);
[Link]("<====After Removing EvenLength ArrayList
Item====>");
for (String str : arrlist)
{
[Link](str);
}
}
}
Output:
<====ArrayList Item====>
Java
C++
DataScience
Python
Cyber
<====After Removing EvenLength ArrayList Item====>
C++
DataScience
Cyber
Write a method swapPairs that switches the order of values in an ArrayList of Strings
in a pairwise fashion. Your method should switch the order of the first two values,
then switch the order of the next two, switch the order of the next two, and so on.
For example, if the list initially stores these values: {"four", "score", "and", "seven",
"years", "ago"} your method should switch the first pair, "four", "score", the second
pair, "and", "seven", and the third pair, "years", "ago", to yield this list: {"score",
"four", "seven", "and", "ago", "years"}
If there are an odd number of values in the list, the final element is not moved.
For example, if the original list had been: {"to", "be", "or", "not", "to", "be", "hamlet"} It
would again switch pairs of values, but the final value, "hamlet" would not be moved,
yielding this list: {"be", "to", "not", "or", "be", "to", "hamlet"}
PROGRAM:
import [Link].*;
class PairDemo
{
public static void swapPairs(ArrayList<String> list) {
for(int i = 0; i <= [Link]() - 2; i += 2) {
String str = [Link](i + 1);
[Link](i + 1, [Link](i));
[Link](i, str);
}
}
}
public class SPair
{
public static void main(String[] args)
{
int n;
String str;
Scanner sr=new Scanner([Link]);
ArrayList<String> arrlist = new ArrayList<String>();
// use add() method to add elements in the list
[Link]("Enter Number of Item to Added in ArrayList");
n=[Link]();
for(int i=1;i<=n;i++)
{
[Link]("Enter Item ");
str=[Link]();
[Link](str);
}
[Link]("<====Before Switches ArrayList Item====>");
[Link]([Link]());
[Link](arrlist);
[Link]("<====After Switches ArrayList Item====>");
[Link]([Link]());
}
}
Output:
Enter Number of Item to Added in ArrayList
6
Enter Item
HOW
Enter Item
ARE
Enter Item
YOU
Enter Item
MY
Enter Item
DEAR
Enter Item
FRIEND
<====Before Switches ArrayList Item====>
[HOW, ARE, YOU, MY, DEAR, FRIEND]
<====After Switches ArrayList Item====>
[ARE, HOW, MY, YOU, FRIEND, DEAR]
Output:
Enter Number of Item to Added in ArrayList
5
Enter Item
HOW
Enter Item
ARE
Enter Item
YOU
Enter Item
MY
Enter Item
FRIEND
<====Before Switches ArrayList Item====>
[HOW, ARE, YOU, MY, FRIEND]
<====After Switches ArrayList Item====>
[ARE, HOW, MY, YOU, FRIEND]
Write a method called alternate that accepts two Lists of integers as its parameters
and returns a new List containing alternating elements from the two lists, in the
following order:
First element from first list
First element from second list
Second element from first list
Second element from second list
Third element from first list
Third element from second list
…
If the lists do not contain the same number of elements, the remaining elements from
the longer list should be placed consecutively at the end. For example, for a first list
of (1, 2, 3, 4, 5) and a second list of (6, 7, 8, 9, 10, 11, 12), a call of alternate(list1,
list2) should return a list containing (1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12). Do not modify
the parameter lists passed in.
PROGRAM:
import [Link].*;
class Alternate
{
public static List<Integer> alternate(List<Integer> list1, List<Integer>
list2) {
Iterator<Integer> i1 = [Link]();
Iterator<Integer> i2 = [Link]();
List<Integer> result = new ArrayList<Integer>();
while([Link]() || [Link]())
{
if ([Link]()) {
[Link]([Link]());
}
if ([Link]()) {
[Link]([Link]());
}
}
return result;
}
}
public class AlternateList
{
public static void main(String[] args){
List<Integer> L1 = new ArrayList<>();
[Link](L1, 1, 2, 3, 4, 5);
List<Integer> L2 = new ArrayList<>();
[Link](L2, 6, 7, 8, 9, 10,11,12);
List<Integer> L3 = new ArrayList<>();
L3=[Link](L1,L2);
[Link](L1);
[Link](L2);
[Link](L3);
}
}
Output:
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10, 11, 12]
[1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12]