0% found this document useful (0 votes)
10 views15 pages

Java Module - 4

The Java Collections Framework provides an architecture for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Map. It allows operations like searching, sorting, and manipulation of data, with specific implementations like ArrayList, HashSet, and HashMap. The framework also includes iterators for traversing collections and comparators for sorting objects based on custom criteria.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views15 pages

Java Module - 4

The Java Collections Framework provides an architecture for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Map. It allows operations like searching, sorting, and manipulation of data, with specific implementations like ArrayList, HashSet, and HashMap. The framework also includes iterators for traversing collections and comparators for sorting objects based on custom criteria.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Collections in Java

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.


o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The [Link] package


contains all the classes and interfaces for the Collection framework.
java Collections Interface MethodsThe table below describes the methods
available to use against Java Collections for data Manipulation Jobs.

Method Description
add() Add objects to collection
isEmpty() Returns true if collection is empty
clear() Removes all elements from the
collection
remove() Remove a selected object
size() Find the number of elements
stream() Return Sequential elements
max() Return max value in the collection
retainAll() Retains elements in the collection

Collection Interface

The Collection interface is the interface which is implemented by all the classes
in the collection framework. It declares the methods that every collection will
have. In other words, we can say that the Collection interface builds the
foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all
the subclasses of Collection interface.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type
data structure in which we can store the ordered collection of objects. It can
have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and


Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

The classes that implement the List interface are given below.

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to
store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored in
the ArrayList class can be randomly accessed. Consider the following example.

1. import [Link].*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Ravi");//Adding object in array
6. list
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.//Traversing list through Iterator
[Link] itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
14.}
15.}
16.}

Output:
Ravi
Vijay
Ravi
Ajay

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list


internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.

Consider the following example.

1. import [Link].*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. [Link]("Ravi");
6. [Link]("Vijay");
7. [Link]("Ravi");
8. [Link]("Ajay");
9. Iterator<String> itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
12.}
13.}
14.}

Output:

Ravi
Vijay
Ravi
Ajay
Vector

Vector uses a dynamic array to store the data elements. It is similar to


ArrayList. However, It is synchronized and contains many methods that are not
the part of Collection framework.

Consider the following example.

1. import [Link].*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. [Link]("Ayush");
6. [Link]("Amit");
7. [Link]("Ashish");
8. [Link]("Garima");
9. Iterator<String> itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
12.}
13.}
14.}

Output:

Ayush
Amit
Ashish
Garima

Set Interface

Set Interface in Java is present in [Link] package. It extends the Collection


interface. It represents the unordered set of elements which doesn't allow us
to store the duplicate items. We can store at most one null value in Set. Set is
implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
HashSet

HashSet class implements Set Interface. It represents the collection that uses a
hash table for storage. Hashing is used to store the elements in the HashSet. It
contains unique items.

Consider the following example.

1. import [Link].*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.//Traversing elements
[Link]<String> itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
14.}
15.}
16.}

Output:

Vijay
Ravi
Ajay

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage.
Like HashSet, TreeSet also contains unique elements. However, the access and
retrieval time of TreeSet is quite fast. The elements in TreeSet stored in
ascending order.

Consider the following example:

1. import [Link].*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.//traversing elements
[Link]<String> itr=[Link]();
[Link]([Link]()){
[Link]([Link]());
14.}
15.}
16.}

Output:

Ajay
Ravi
Vijay
Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis
of a key.

Java HashMap

Java HashMap class implements the Map interface which allows us to


store key and value pair, where keys should be unique. If you try to insert
the duplicate key, it will replace the element of the corresponding key. It
is easy to perform operations using the key index like updation, deletion,
etc. HashMap class is found in the [Link] package.

HashMap in Java is like the legacy Hashtable class, but it is not


synchronized. It allows us to store the null elements as well, but there
should be only one null key. Since Java 5, it is denoted as HashMap<K,V>,
where K stands for key and V for value. It inherits the AbstractMap class
and implements the Map interface.

Points to remember
o Java HashMap contains values based on the key.
o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.

void clear() It is used to remove all of the mappings from this


map.

boolean isEmpty() It is used to return true if this map contains no key-


value mappings.

Object clone() It is used to return a shallow copy of this HashMap


instance: the keys and values themselves are not
cloned.

Set entrySet() It is used to return a collection view of the mappings


contained in this map.

Set keySet() It is used to return a set view of the keys contained in


this map.

V put(Object key, Object It is used to insert an entry in the map.


value)

void putAll(Map map) It is used to insert the specified map in the map.

V remove(Object key) It is used to delete an entry for the specified key.

boolean This method returns true if some value equal to the


containsValue(Object value exists within the map, else return false.
value)

boolean This method returns true if some key equal to the key
containsKey(Object key) exists within the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with the


Map.

V get(Object key) This method returns the object that contains the
value associated with the key.

boolean isEmpty() This method returns true if the map is empty; returns
false if it contains at least one key.

V replace(K key, V value) It replaces the specified value for a specified key.

int size() This method returns the number of entries in the


map.

Java HashMap Example:


1. import [Link].*;
2. public class HashMapExample1{
3. public static void main(String args[]){
4. HashMap<Integer,String> map=new HashMap<Integer,String>();//
Creating HashMap
5. [Link](1,"Mango"); //Put elements in Map
6. [Link](2,"Apple");
7. [Link](3,"Banana");
8. [Link](4,"Grapes");
9.
10. [Link]("Iterating Hashmap...");
11. for([Link] m : [Link]()){
12. [Link]([Link]()+" "+[Link]());
13. }
14. }
15. }
Test it Now
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes

Java Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values.
It inherits Dictionary class and implements the Map interface.

Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The
position of the bucket is identified by calling the hashcode() method. A
Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.

ava Hashtable Example


1. import [Link].*;
2. class Hashtable1{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. [Link](100,"Amit");
7. [Link](102,"Ravi");
8. [Link](101,"Vijay");
9. [Link](103,"Rahul");
10.
11. for([Link] m:[Link]()){
12. [Link]([Link]()+" "+[Link]());
13. }
14. }
15.}
Test it Now

Output:

103 Rahul
102 Ravi
101 Vijay
100 Amit

Java Hashtable Example: remove()


1. import [Link].*;
2. public class Hashtable2 {
3. public static void main(String args[]) {
4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();
5. [Link](100,"Amit");
6. [Link](102,"Ravi");
7. [Link](101,"Vijay");
8. [Link](103,"Rahul");
9. [Link]("Before remove: "+ map);
10. // Remove value for key 102
11. [Link](102);
12. [Link]("After remove: "+ map);
13. }
14.}

Output:

Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


After remove: {103=Rahul, 101=Vijay, 100=Amit}

Accessing a Java Collection via a Iterator

The java collection framework often we want to cycle through the elements.
For example, we might want to display each element of a collection. The java
provides an interface Iterator that is available inside the [Link] package to
cycle through each element of a collection.

🔔 The Iterator allows us to move only forward direction.

🔔 The Iterator does not support the replacement and addition of new
elements.

We use the following steps to access a collection of elements using the


Iterator.

[Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class JavaIteratorExample {
5. public static void main(String[] args)
6. {
7. ArrayList<String> cityNames = new ArrayList<String>();
8.
9. [Link]("Delhi");
10. [Link]("Mumbai");
11. [Link]("Kolkata");
12. [Link]("Chandigarh");
13. [Link]("Noida");
14.
15. // Iterator to iterate the cityNames
16. Iterator iterator = [Link]();
17.
18. [Link]("CityNames elements : ");
19.
20. while ([Link]())
21. [Link]([Link]() + " ");
22.
23. [Link]();
24. }
25. }

Output:

CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida

Java Comparator interface


Java Comparator interface is used to order the objects of a user-
defined class.

This interface is found in [Link] package and contains 2 methods


compare(Object obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on
the basis of any data member, for example, rollno, name, age or anything
else.

Methods of Java Comparator Interface


Method Description

public int compare(Object obj1, It compares the first object with the second object.
Object obj2)

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Java Comparator Example (Non-generic Old


Style)
Let's see the example of sorting the elements of List on the basis of age
and name. In this example, we have created 4 java classes:

1. [Link]
2. [Link]
3. [Link]
4. [Link]

[Link]
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=age;
9. }
10. }
[Link]
1. import [Link].*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if([Link]==[Link])
5. return 0;
6. else if([Link]>[Link])
7. return 1;
8. else
9. return -1;
10. }
11. }
[Link]

This class provides comparison logic based on the name. In such case, we
are using the compareTo() method of String class, which internally
provides the comparison logic.

1. import [Link].*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return [Link]([Link]);
5. }
6. }
[Link]

In this class, we are printing the values of the object by sorting on the
basis of name and age.

1. import [Link].*;
2. import [Link].*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. [Link](new Student(101,"Vijay",23));
8. [Link](new Student(106,"Ajay",27));
9. [Link](new Student(105,"Jai",21));
10. [Link]("Sorting by Name");
11.
12. [Link](al,new NameComparator());
13. for(Student st: al){
14. [Link]([Link]+" "+[Link]+" "+[Link]);
15. }
16.
17. [Link]("Sorting by age");
18.
19. [Link](al,new AgeComparator());
20. for(Student st: al){
21. [Link]([Link]+" "+[Link]+" "+[Link]);
22. }
23. }
24. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparable interface


Java Comparable interface is used to order the objects of the user-defined
class. This interface is found in [Link] package and contains only one
method named compareTo(Object). It provides a single sorting sequence
only, i.e., you can sort the elements on the basis of single data member
only. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method


public int compareTo(Object obj): It is used to compare the current
object with the specified object. It returns

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
Java Comparable Example
Let's see the example of the Comparable interface that sorts the list
elements on the basis of age.

File: [Link]

1. class Student implements Comparable<Student>{


2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=age;
9. }
10. public int compareTo(Student st){
[Link](age==[Link])
[Link] 0;
[Link] if(age>[Link])
[Link] 1;
[Link]
[Link] -1;
17.}
18.}

File: [Link]

1. import [Link].*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. [Link](new Student(101,"Vijay",23));
6. [Link](new Student(106,"Ajay",27));
7. [Link](new Student(105,"Jai",21));
8.
9. [Link](al);
[Link](Student st:al){
[Link]([Link]+" "+[Link]+" "+[Link]);
12.}
13.}
14.}
105 Jai 21
101 Vijay 23
106 Ajay 27
Difference between Comparable and
Comparator
Comparable and Comparator both are interfaces and can be used to sort
collection elements.

However, there are many differences between Comparable and


Comparator interfaces that are given below.

Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple


sequence. In other words, we can sort the sorting sequences. In other words, we
collection on the basis of a single element can sort the collection on the basis of
such as id, name, and price. multiple elements such as id, name, and
price etc.

2) Comparable affects the original class, Comparator doesn't affect the


i.e., the actual class is modified. original class, i.e., the actual class is
not modified.

3) Comparable provides compareTo() Comparator provides compare()


method to sort elements. method to sort elements.

4) Comparable is present A Comparator is present in


in [Link] package. the [Link] package.

5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by [Link](List) method. by [Link](List,
Comparator) method.

You might also like