Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views19 pages

Collections

Uploaded by

med.elbouti0101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

Collections

Uploaded by

med.elbouti0101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

www.kiran-khanal.com.

np

BEGINNER’S GUIDE TO
JAVA COLLECTIONS
Explore Java Collections — the foundation
of flexible, efficient data handling in
modern Java applications.

Swipe for more


Page 1 www.kiran-khanal.com.np

Java Collection is a popular framework to store and


manipulate the group of objects in Java. The Java
Collection Framework (JCF) provides a set of
interfaces and classes to implement various types of
data structures and algorithms. It gives programmers
access to prepackaged data structures and algorithms
for manipulating them.

Collections are the one-stop solution for all sorts of


data manipulation jobs, such as storing data,
searching, sorting, insertion, updating, and deletion.

In simpler terms, the Java Collections Framework


helps you manage a group of objects and perform
operations on them efficiently. It is a predefined
architecture capable of storing a group of elements
and making them behave as a single entity, such as an
object.

Before JCF, developers had to rely on custom data


structures or limited APIs like Vector and Hashtable.
JCF brought consistency, flexibility, and performance
to the table.
Page 2 www.kiran-khanal.com.np

🔗 Core Interfaces of Java Collections


🧱 LIST : An Ordered Collection
The List interface in Java represents an ordered
collection that allows duplicate elements. It is a part of
java.util package. The elements are stored in the order
that they were added; hence, it maintains the insertion
order.
List also provides indexed access, allowing developers
to retrieve or modify elements by their position in the
list.
Some of the most commonly used implementations of
the List interface include ArrayList, LinkedList, and
Vector. Each of these interfaces has its own
performance characteristics and use cases.
Page 3 www.kiran-khanal.com.np

💡 Common Implementation of List


📦 ArrayList
ArrayList is a dynamic array-based implementation. It is
fast for get and set operations but slower for insertion
and deletion in the middle of the list.

🔗 LinkedList
LinkedList is an implementation of a doubly linked list. It
excels in insertions and deletions but may be slower for
access due to its non-contiguous memory structure,
meaning that the elements are not stored next to each
other. Instead, each element, called a node, contains actual
data and a reference (pointer) to both the previous and the
next node on the list.

🛡️ Vector
Vector is a class in Java that implements the List
interface and works like an ArrayList, but with one key
difference—it is synchronized. This means it is thread-
safe and can be safely used in multi-threaded
environments. However, because of this synchronization,
Vector is usually slower than ArrayList in single-threaded
situations.
Page 4 www.kiran-khanal.com.np

🥞 Stack
Stack is a class in Java that represents a Last-In, First-
Out (LIFO) data structure. It extends the Vector class and
provides methods like push() to add elements, pop() to
remove the top element, and peek() to look at the top
element without removing it. Since it inherits from
Vector, it's also synchronized by default.

Feature ArrayList LinkedList Vector Stack

Dynamic
Dynamic Doubly Dynamic
Backed By Array (via
Array Linked List Array
Vector)

Fast for Fast of Slower due LIFO


Performance
access insert/delete to sync operations

Order
Yes Yes Yes Yes
Maintained

Thread-Safe No No Yes Yes

Not typically
Index Access Fast Slow Fast
used
Page 5 www.kiran-khanal.com.np

Core Methods of the List Interface 🛠️


➕ add(element)
The add() method adds an element to the list.

🔍 get(index)
The get() method retrieves the element at the specified
index.

✏️ set(index, element)
The set() method replaces the element at the specified
index.
Page 6 www.kiran-khanal.com.np

❌ remove(index or element)
The remove() method removes an element by index or by
value.

✅ contains(element)
The contains() method checks if the list contains the
given element.

🔢 indexOf(element)
The indexOf() method returns the index of the first
occurrence.
Page 7 www.kiran-khanal.com.np

🧹 clear()
The clear() method removes all the elements in the list.

📏 size()
The size() method returns the number of elements in the
list.
Page 8 www.kiran-khanal.com.np

🔗 Core Interfaces of Java Collections


🔁 SET : Unordered Collection
The Set interface in Java represents a collection of
unique elements. Unlike a List, a Set does not allow
duplicate values, making it ideal when you want to
ensure that every item is distinct — like storing unique
IDs, tags, or usernames.
Sets do not maintain any specific order by default, and
they also don’t allow accessing elements by index. This
is because Sets are designed to focus on the presence of
elements, not their position.
Some of the most commonly used implementations of
the Set interface include HashSet, LinkedHashSet, and
Treeset.
Page 9 www.kiran-khanal.com.np

💡 Common Implementation of Set


⚡ HashSet
HashSet is the most commonly used Set implementation.
It doesn’t guarantee any specific order of elements — the
items may appear in a different order each time you run
your code. However, it offers constant-time performance
for basic operations like add, remove, and contains.

📋 LinkedHashSet
LinkedHashSet extends HashSet and adds a twist — it
maintains the insertion order of elements. This means when
you iterate over the set, the elements will appear in the
same order in which they were added. It’s slightly slower
than HashSet, but useful when you need both uniqueness
and order.

🌲 TreeSet
TreeSet implements the NavigableSet interface and stores
elements in a sorted (natural) order — alphabetically for
strings, numerically for numbers. It uses a Red-Black tree
under the hood, making operations a bit slower than
HashSet, but perfect when you want the elements to stay
sorted automatically.
Page 10 www.kiran-khanal.com.np

Core Methods of the Set Interface 🛠️


➕ add(element)
The add() method adds an element to the set.

❌ remove(Object element)
The remove() method removes the specified item from
the set, if present.

🔍 contains(Object element)
The contains() method checks if a specific element exists
in the set.
Page 11 www.kiran-khanal.com.np

🔁 clear()
Removes all elements from the set. (same as List)

📏 size()
Returns the number of elements in the set.

📦 isEmpty()
Checks whether the set is empty.

🔁 forEach() / enhanced for loop


Used to iterate through the elements in the set.
Page 12 www.kiran-khanal.com.np

🗺️ Map Interface in Java


The Map interface in Java represents a collection of key-
value pairs, where each key is unique, and each key
maps to exactly one value. Unlike List or Set, a Map is
not a subtype of the Collection interface, but it's an
equally essential part of the Java Collections
Framework.
In a Map, each key must be unique. However, values can
be duplicated — multiple keys can point to the same
value. If you try to insert a new value using an existing
key, the old value gets replaced with the new one,
keeping the key unique in the map.
Some of the most commonly used implementations of
the Map interface include HashMap, LinkedHashMap,
and TreeMap.
Page 13 www.kiran-khanal.com.np

💡 Common Implementation of Map


⚡ HashMap
HashMap is the most commonly used implementation of
the Map interface. It allows storing key-value pairs with no
guaranteed order of keys — the elements may appear in a
different sequence each time you access them. HashMap
offers fast performance for basic operations like
insertion, deletion, and lookup.

📋 LinkedHashMap
LinkedHashMap is a subclass of HashMap that maintains the
insertion order of entries — meaning keys are returned in the
order they were added. This makes it useful when the order
of elements matters. However, due to the extra overhead of
maintaining this order, it is slightly slower than a regular
HashMap in terms of performance.

🌲 TreeMap
TreeMap is a sorted map implementation that stores its keys
in natural order (like alphabetical for strings or ascending
for numbers), or according to a custom comparator. It’s
ideal when you need the data to be automatically sorted by
key. The benefit is having a consistently ordered map
without additional sorting logic.
Page 14 www.kiran-khanal.com.np

Core Methods of the Map Interface 🛠️


🔑 put(key, value)
Adds a key-value pair. Replaces the value if the key
already exists.

🔍 get(key)
Returns the value for the given key (or null if not found).

❌ remove(key)
Removes the key and its associated value from the map.
Page 15 www.kiran-khanal.com.np

✅ containsKey(key)
Checks if a key exists in the map.

🔎 containsValue(value)
Checks if a value exists in the map.

🗝️ keySet()
Returns a Set of all the keys.

📦 values()
Returns a collection of all the values.
Page 16 www.kiran-khanal.com.np

🧩 entrySet()
Returns a Set of all key-value pairs as Map.Entry.

📏 size()
Returns the number of key-value pairs.

📭 isEmpty()
Checks if the map is empty.

🧹 clear()
Removes all entries from the map.

🚪 putIfAbsent(key, value)
Adds only if the key isn’t already in the map.
Page 17 www.kiran-khanal.com.np

🔁 replace(key, value)
Replaces the value only if the key already exists.

🔄 forEach((k,v) -> {...})


Iterates over each key-value pair using a lambda/action.
Kiran Khanal Software Engineer

If you
find this
helpful, please
like and share
it with your
friends
www.linkedin.com/kirankhanalleo

You might also like