0% found this document useful (0 votes)
18 views34 pages

Chapter 16 - Collection API - 2

The document provides an overview of the Collection API in Java, explaining its components, including Collection, Collections, and various interfaces like List, Set, and Map. It highlights the advantages of using the Collection API over traditional arrays, such as dynamic sizing, support for heterogeneous data, and built-in methods for data manipulation. Additionally, it discusses the hierarchy of the Collection interface and provides examples of using different collection types and their methods.

Uploaded by

Adamu Tiruneh
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)
18 views34 pages

Chapter 16 - Collection API - 2

The document provides an overview of the Collection API in Java, explaining its components, including Collection, Collections, and various interfaces like List, Set, and Map. It highlights the advantages of using the Collection API over traditional arrays, such as dynamic sizing, support for heterogeneous data, and built-in methods for data manipulation. Additionally, it discusses the hierarchy of the Collection interface and provides examples of using different collection types and their methods.

Uploaded by

Adamu Tiruneh
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

Modern Programming

Practices with Java

Instructor: Solomon (Ph.D)


Chapter 16: The Collection API
The Collection API

commonly
Introduction to the Collection API
• In Java, the term Collection API can be confusing because
it involves three related terms: Collection API, Collection,
and Collections. Although they sound similar, each has a
distinct meaning:
1) Collection API (or Java Collections Framework) - is the entire
framework that provides classes and interfaces for storing
and manipulating groups of objects. It includes:
✓ Interfaces – such as Collection, List, Set, Queue, and Map.
✓ Classes – such as ArrayList, LinkedList, HashSet, TreeSet,
HashMap.
✓ Algorithms and utility methods – provided by the Collections
class.
o The Collection API helps programmers:
✓ Store groups of objects dynamically.
✓ Perform operations such as searching, sorting, inserting, deleting.
✓ Use standardized data structures.
Introduction to the Collection API …
2) Collection – is an interface in the [Link] package that
represents a group of objects. It is the root interface of the Java
Collection hierarchy, and interfaces such as List, Set, and Queue
extend it. The Map interface is not part of this hierarchy. It
defines basic operations such as:
✓ add() - Adds an element to the collection.
✓ remove() - Removes a specific element from the collection.
✓ size() - Returns the number of elements stored in the collection.
✓ clear() - Removes all elements from the collection.
✓ contains() - Checks whether a specific element exists in the collection.
3) Collections - is a utility class in [Link] package. It provides
static methods that operate on collection objects. It provides
various algorithms such as sorting, searching and shuffling.
✓ sort() - Sorts a list.
✓ reverse() - Reverses elements.
✓ shuffle() - Randomly rearranges elements.
✓ max() - Returns the maximum element.
✓ min() - Returns the minimum element.
Introduction to the Collection API …
• Example:
import [Link];
import [Link];
import [Link];

public class Demo {


public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
[Link](5);
[Link](2);
[Link](8);

[Link](nums);

[Link](nums);
}
}
Output:
[2, 5, 8]
Why Use the Collection API?
• Before the introduction of the Collection API, Java
developers mainly relied on arrays to store data. While
arrays are useful, they come with some limitations:
▪ Fixed Size - Once an array is declared, its size is fixed and cannot
be changed. If more elements need to be added, a new array of a
larger size must be created, and existing elements must be
manually copied to the new array. This approach is not efficient in
terms of time and memory.
▪ Homogeneous Data - Arrays can only store elements of a single
data type. For example, if we need to store details about a
student (such as name, age, height, and weight), using a single
array would be insufficient. While an array of objects can be
created, managing multiple objects becomes cumbersome.
▪ Complex Operations - Operations like sorting, inserting or
removing elements in an array require manual implementation,
which can be error-prone and time-consuming.
Why Use the Collection API? …
• These limitations made arrays less optimal for working
with complex data structures. To address these issues, the
Collection API provides various data structures that are
flexible and easier to use.
Advantages of the Collection API
• The Collection API offers several benefits that make it
preferable over arrays:
▪ Dynamic Sizing - Data structures like ArrayList can grow or shrink
in size depending on the number of elements. This dynamic nature
helps manage data more efficiently.
▪ Support for Heterogeneous Data - Unlike arrays, collection classes
can store different types of data in a single structure. For instance,
an ArrayList can hold a mixture of strings, integers or other
objects.
▪ Built-in Methods for Data Manipulation - Collection implementing
classes comes with built-in methods for operations like sorting,
inserting, searching and deleting, making these tasks simpler.
▪ Efficient Memory Usage – Many collection classes (such as
ArrayList and HashMap) dynamically resize their internal storage
as elements are added or removed. This means programmers do
not need to manually manage the size of the data structure.
Advantages of the Collection API …
• Example: Storing Heterogeneous Data in an ArrayList
import [Link];

public class Demo {


public static void main(String[] args) {
ArrayList list = new ArrayList();

[Link]("Hello"); // String
[Link](100); // Integer
[Link](45.6); // Double
[Link](true); // Boolean

[Link](list);
}
}
Output:
[Hello, 100, 45.6, true]
Components of the Collection API
• The Collection API consists of multiple classes and
interfaces, each serving specific purposes. Here’s a brief
overview of some commonly used components:
▪ List Interface - represents an ordered collection (sequence) of
elements. Examples include ArrayList, LinkedList, and Vector.
▪ Set Interface - represents a collection that does not allow duplicate
elements. Examples include HashSet, LinkedHashSet and TreeSet.
▪ Queue Interface - represents a collection designed for holding
elements prior to processing. Examples include PriorityQueue and
ArrayDeque.
▪ Map Interface - represents a collection of key-value pairs. Examples
include Hashtable, HashMap, LinkedHashMap and TreeMap.
• Each of these interfaces and their implementations
provide different functionalities, allowing developers to
choose the appropriate data structure based on their
requirements.
Comparison with Arrays
• The Collection API offers significant advantages over
traditional arrays:
Feature Arrays Collection API
Size Fixed Dynamic (can grow/shrink)

Data Type Homogeneous Can be homogeneous or


heterogeneous

Built-in Methods Limited Rich set of methods for


data manipulation

Performance Manual implementation Methods for efficient


(Insertion, Deletion) required operations

Memory Requires manual Automatic resizing


Management resizing
Hierarchy of the Collection Interface
• The Java Collections Framework (often called the
Collection API) was introduced in Java SE 1.2 to enhance
array operations and provide a set of standard interfaces
and classes for handling data.
▪ It includes a variety of interfaces and classes with many built-in
methods for data manipulation. To use the Collections
Framework, you need to import the [Link] package, which
contains these interfaces and classes.
• Previously, most code did not require importing external
packages because the core classes were included in the
[Link] package. This package automatically imports
classes like Object, the superclass of all classes in Java.
▪ Similarly, the Collections API is part of the [Link] package,
which is also known as the utility package because it provides
methods for various tasks such as sorting and data insertion.
Hierarchy of the Collection Interface …

• The top-level interface in the Collections Framework is


Iterable, followed by the Collection interface. The
Collection interface is then extended by the most
Hierarchy of the Collection Interface …
commonly used interfaces, such as List, Queue and Set. Each of
these interfaces has its own set of implementing classes, which
provide specific functionalities.
▪ List Interface - Implemented by classes such as ArrayList,
LinkedList and Vector.
▪ Queue Interface - Implemented by classes such as PriorityQueue.
The Deque interface, which extends Queue, is implemented by
classes like ArrayDeque.
▪ Set Interface - Commonly used in more advanced topics. It is
implemented by classes such as HashSet, LinkedHashSet and
TreeSet.
▪ Map Interface - Although not directly under the Collection
hierarchy, the Map interface is part of the Java Collections
Framework. It stores data in key-value pairs and is implemented
by classes like Hashtable, HashMap, LinkedHashMap and
TreeMap.
1. List interface
• In Java, one of the most commonly used interfaces in
the Collections framework is the List interface, which
allows duplicate elements and supports operations
like adding, sorting, and inserting and fetching
elements based on index.
• Two popular classes implementing the List interface
are ArrayList and LinkedList.
− These classes allow you to add duplicate elements and
maintain the order in which elements were inserted.
Example of using a Collection
• Let’s look at a simple example using the Collection
interface with the ArrayList class.
import [Link];
import [Link];

public class Demo {


public static void main(String[] args) {
// Using Collection interface with ArrayList implementation
Collection<Integer> nums = new ArrayList<>();
[Link](3);
[Link](4);
[Link](5);
[Link](9);
[Link](8);
[Link](7);

// Printing the ArrayList


[Link](nums);
}
}
Output:
[3, 4, 5, 9, 8, 7]
Example of using a Collection …
• Printing Separate Values Using a Loop:
for(Integer num: nums) {
[Link](num);
}

• Accessing Elements by Index:


– If you need to access elements by their index, use the List
interface as the Collection interface doesn’t have methods
to work with indexing which List provides, a get(int index)
method to retrieve the element at a specific position.
List<Integer> numList = new ArrayList<>(nums);

[Link]("Element at index 2: " + [Link](2));

Output:
5
Example of using a List
• Let’s look at a simple example using the List interface with
the ArrayList class.
import [Link].*;
public class Demo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
[Link](82);
[Link](11);
[Link](16);
[Link](82); // Duplicate element
for(int num: nums) {
[Link](num);
}
}
}
Output:
82
11
16
82

• In the above example, duplicate elements (82) are allowed.


However, if you need to store unique values where duplicates
are not permitted, the Set interface is the appropriate choice.
2. Set Interface
• The Set interface is a part of the Collections framework in
Java, designed to hold a collection of unique elements. It
does not allow duplicate values and provides
functionalities to ensure all elements in the collection are
distinct.

• Characteristics of Set Interface:


– Extends the Collection interface.
– Guarantees that no duplicate elements are present.
– Implemented by classes like HashSet, LinkedHashSet (for index-
based operations), and TreeSet (for ordered Sorting of elements).

• Syntax for Declaring a Set:


Set<Integer> values = new HashSet<Integer>();
Implementing Classes of Set Interface
▪ HashSet:
– Does not maintain any order of elements.
– Uses a hashing algorithm for storing elements, making
retrieval fast.
▪ LinkedHashSet:
− Maintains the insertion order of elements.
− Slower than HashSet due to the maintenance of the order.
▪ TreeSet:
− Stores elements in sorted order (ascending).
− Implements the NavigableSet interface, which extends the
SortedSet interface.
− Ensures that elements are both unique and sorted.
Methods in Set Interface
▪ add()
− The add() method is used to insert elements into the set. If an
element already exists in the set, it will not be added again (no
duplicates are allowed).
− Example: Using HashSet
import [Link].*;

public class Demo {


public static void main(String[] args) {
Set<Integer> values = new HashSet<>();
[Link](82);
[Link](11);
[Link](16);
[Link](4);
[Link](3); Output:
[Link](82); // Duplicate element 16
for(int num: values) { 82
[Link](num);
}
3
} 4
} 11
Methods in Set Interface …
• Explanation:
− The output may not appear in the order in
which the elements were added. This is
because HashSet does not maintain insertion
order.
− Duplicate values (82) are removed
automatically as Set Supports only Unique
values.
• Using TreeSet for sorted and unique values:
− If you need a collection where the elements are
both unique and sorted, you should use the
TreeSet class.
− The TreeSet class implements the NavigableSet
interface, which extends the SortedSet
interface. As a result, elements are stored in a
sorted manner.
Example: Using TreeSet
import [Link].*;
public class Demo {
public static void main(String[] args) {
Set<Integer> values = new TreeSet<>();
[Link](82);
[Link](11);
[Link](16);
[Link](4);
[Link](3);
[Link](82); // Duplicate element
for(int num: values) { Output:
[Link](num); 3
} 4
} 11
} 16
82

• The output is sorted in ascending order because of the


TreeSet implementation.
• Duplicate values are not added.
Understanding the Iterable Interface
• The Iterable interface is the top-most interface in the
Collections framework, which allows for iterating over a
collection. It provides the ability to traverse the elements
using an iterator.
• Example: Using Iterator with TreeSet
import [Link].*;
public class Demo {
public static void main(String[] args) {
Set<Integer> values = new TreeSet<>();
[Link](82);
[Link](11);
[Link](16);
[Link](4);
[Link](3);
[Link](82); // Duplicate element
Iterator<Integer> iterator = [Link]();
while([Link]()) {
[Link]([Link]());
}
}
}
Understanding the Iterable Interface …
• Output:
3
4
11
16
82

• Methods in Iterator:
✓ hasNext(): Checks if there are more elements in the
collection.
✓ next(): Retrieves the next element in the collection.
3. Map Interface
• The Map interface is part of the Java Collections
Framework, although it does not extend the Collection
interface.
• In Java, a Map represents a collection of key-value pairs,
where each unique key maps to a specific value.
− This concept is similar to a telephone directory, where a person’s
name (key) is associated with a phone number (value). When you
provide a key, the corresponding value can be retrieved.
• Features of Map Interface:
✓ Mapping between Keys and Values - The Map interface allows for
the association of unique keys with specific values.
✓ Unique Keys - Each key in a Map must be unique, while values can be
duplicated.
✓ Not a Subtype of Collection Interface - Unlike other collection types,
Map is not a subtype of the Collection interface, so it behaves
differently.
Creating Map Objects
• Since Map is an interface, you cannot create objects of
the Map type directly.
− You must use a class that implements the Map interface to
create an object, such as Hashtable, HashMap,
LinkedHashMap or TreeMap.

• Syntax for Creating a Map:


Map<ObjectType1, ObjectType2> mapName = new HashMap<>();
▪ The ObjectType1 represents the type of the keys, while
ObjectType2 represents the type of the values.
Creating Map Objects …
• Example: Storing Student Names and Marks
− Here’s how you can create a Map to store student names (as
keys) and their marks (as values)
import [Link];
import [Link];

public class Demo {


public static void main(String[] args) {
Map<String, Integer> studs = new HashMap<>();
[Link]("Abel", 56);
[Link]("Sara", 65);
[Link]("Selam", 73);
[Link]("Meron", 96);

[Link](studs);
}
}
Output:
{Meron=96, Abel=56, Selam=73, Sara=65}
Creating Map Objects …
• Explanation:
− We created a Map object named studs using HashMap, specifying
the key type as String and the value type as Integer.
− The put() method is used to add key-value pairs to the map.
− When we print the studs map, it displays the names and their
corresponding marks.
• Working with Map Elements:
✓ Accessing Values - You can retrieve a value from the map using
the get() method by providing the corresponding key. For
example, [Link]([Link]("Sara"));
▪ Output: 65
✓ Handling Duplicate Keys - If you add a key that already exists in
the map, the new value will replace the old value. For instance,
[Link]("Sara", 45);
[Link](studs);
▪ Output: {Meron=96, Abel=56, Selam=73, Sara=45}
Iterating Over a Map
• To separate keys and values or iterate through the map, you
can use a for-each loop with methods like keySet() to get all
keys.
• Example: Iterating Over Keys and Values
import [Link];
import [Link];
public class Demo {
public static void main(String[] args) {
Map<String, Integer> studs = new HashMap<>();
[Link]("Abel", 56);
[Link]("Sara", 45);
[Link]("Selam", 73);
[Link]("Meron", 96);
for(String name: [Link]()) { Output:
[Link](name + ": " + [Link](name)); Meron: 96
} Abel: 56
}
Selam: 73
Sara: 45
}

▪ The keySet() method retrieves only the keys from the map, and
we use the get() method to get corresponding values.
Important Methods of the Map
Interface
• Below is a list of commonly used methods in the Map
interface along with their descriptions:
Method Description Time Complexity

put(Key, Value) Associates the specified key O(1)


with the specified value in the
map.
get(Key) Returns the value associated O(1)
with the specified key.
containsKey(Key) Checks if the map contains the O(1)
specified key. Returns true if it
does, otherwise false.

containsValue(Value) Checks if the map contains the O(n)


specified value. Returns true if
it does, otherwise false.
Important Methods of the Map
Interface …
Method Description Time Complexity

isEmpty() Returns true if the map contains no key- O(1)


value pairs.
clear() Removes all key-value pairs from the O(n)
map.
remove(Key) Removes the mapping for a key from O(1)
this map if it is present.
size() Returns the number of key-value O(1)
mappings in the map.
… … …

• Hashtable vs. HashMap:


✓ HashMap - allows null keys and values, and is not synchronized
(not thread-safe).
✓ Hashtable - does not allow null keys or values, and is
synchronized (thread-safe).
THE END!

You might also like