0% found this document useful (0 votes)
8 views

Java Collections Framework(29!03!25)

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Collection, List, Set, and their implementations like ArrayList, HashSet, and TreeSet. It explains the functionalities of these interfaces, including methods for adding, removing, and accessing elements, as well as the characteristics of each collection type. Additionally, it includes examples demonstrating the usage of these collections in Java programming.

Uploaded by

sarithainti444
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 views

Java Collections Framework(29!03!25)

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Collection, List, Set, and their implementations like ArrayList, HashSet, and TreeSet. It explains the functionalities of these interfaces, including methods for adding, removing, and accessing elements, as well as the characteristics of each collection type. Additionally, it includes examples demonstrating the usage of these collections in Java programming.

Uploaded by

sarithainti444
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/ 15

Collections Framework

Collections:
 Collection is a framework that provides architecture to store and manipulate the
group of objects.
 It can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
 A Collection represents a single unit of objects, i.e., a group.
 Java Collection framework provides many interfaces (Collection, List, Set and Sorted
Set) and classes (Array List, HashSet, and TreeSet)
 It provides readymade architecture.

Collection Interfaces:
 Collection Interface
 List Interfae
 Set Interface
 Sorted Set Interface

Collection classes:
 Array List
 HashSet
 TreeSet

Hash Map Accessing a Collection via an Iterator:


.
Collection Interface

 The Collection interface is a member of the java collections framework


 It is a part of java.util package.
 It is one of the root interfaces of the Collection Hierarchy.
 The Collection interface is not directly implemented by any class.
 The Collection interface is the interface which is implemented by all the classes in the
collection framework.

Here List, Set and Queue are sub interfaces of Collection interface.

The Collection interface includes various methods that can be used to perform different
operations on objects. These methods are available in all its sub interfaces.

add() - inserts the specified element to the collection


size() - returns the size of the collection
remove() - removes the specified element from the collection
iterator() - returns an iterator to access elements of the collection
addAll() - adds all the elements of a specified collection to the collection
removeAll() - removes all the elements of the specified collection from the collection
clear() - removes all the elements of the collection
etc…
.
Example:
import java.io.*;
import java.util.*;
public class CollectionDemo {
public static void main(String args[])
{
// creating an empty LinkedList
Collection<String> list = new LinkedList<String>();

// use add() method to add elements in the list


list.add("One");
list.add("Two");
list.add("Three");

// Output the present list


System.out.println("The list is: " + list);
}
}

Here LinkedList is one of the sub classes of List interface and List is the sub interface of
Collection interface.

Output:
The list is: [One, Two, Three]
List Interface

 List in Java provides the facility to maintain the ordered collection.


 It contains the index-based methods to insert, update, delete and search the elements.
 It can have the duplicate elements also.
 We can also store the null elements in the list.
 The List interface is found in the java.util package and inherits the Collection interface.
 The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.

The List interface contains various methods

void add (int index, E element)


It is used to insert the specified element at the specified position in a list.

boolean add (E e)
It is used to append the specified element at the end of a list.

void clear ()
It is used to remove all of the elements from this list.

Eget (int index)


It is used to fetch the element from the particular position of the list.
etc…
Example

import java.util.*;
public class ListExample1
{
public static void main(String args[])
{
//Creating a List
List<String> list=new ArrayList<String>();

//Adding elements in the List


list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");

//Iterating the List element using for-each loop


for(String fruit:list)
System.out.println(fruit);
}
}

Output:
Mango
Apple
Banana
Grapes
Set Interface

 The set is an interface available in the java.util package.


 The set interface extends the Collection interface.
 An unordered collection or list in which duplicates are not allowed is referred to as a
collection interface.
 The set interface use collection interface's methods to avoid the insertion of the same
elements.

The Set interface includes various methods

add (element)
This method is used to add a specific element to the set. The function adds the element only
if the specified element is not already present in the set else the function returns False if the
element is already present in the Set.

addAll (collection)
This method is used to append all of the elements from the mentioned collection to the
existing set. The elements are added randomly without following any specific order.

contains(element)
This method is used to check whether a specific element is present in the Set or not.
isEmpty()
This method is used to check whether the set is empty or not.

iterator()
This method is used to return the iterator of the set. The elements from the set are returned in
a random order.

remove(element)
This method is used to remove the given element from the set. This method returns True if
the specified element is present in the Set otherwise it returns False.
Etc..

Example:
import java.util.*;
public class SetHash
{
public static void main(String[] args)
{

Set<String>hash_Set = new HashSet<String>();

hash_Set.add("One");
hash_Set.add("Two");
hash_Set.add("Three");
hash_Set.add("Four");

hash_Set.add(“Two”); // This element is not added into the list

System.out.println(hash_Set);
}
}

Output:
[One, Four, Two, Three]

Note: Set interface not allowed duplicated elements


Sorted Set

 SortedSet is the alternate of Set interface that provides a total ordering on its elements.

 The elements of the SortedSet are arranged in the increasing (ascending) order.

 The SortedSet provides the additional methods that inhibit the natural ordering of the
elements.

 All the elements must be mutually comparable.

The SortedSet interface includes various methods


comparator()
Returns the comparator which is used to order the elements in the given set. Also returns null
if the given set uses the natural ordering of the element.

first()
Returns the first element from the current set.

last()
Returns the reverse order view of the mapping which present in the map.
Etc..
Example:
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.*;

public class Test


{
public static void main(String[] args)
{
// Create a TreeSet and inserting elements
SortedSet<Integer> s = new TreeSet<>();

// Adding Element to SortedSet


s.add(1);
s.add(5);
s.add(2);
s.add(3);
s.add(9);

// Returning the lowest element from set


System.out.println("Lowest element in set is : "+ s.first());

}
}

Output:
Lowest element in set is : 1
Example:
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.*;

public class Test


{
public static void main(String[] args)
{
// Create a TreeSet and inserting elements
SortedSet<Integer> s = new TreeSet<>();

// Adding Element to SortedSet


s.add(1);
s.add(5);
s.add(2);
s.add(3);
s.add(9);

// Print all elements from Sortedset


Iterator<Integer> i = s.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}

Output:
1
2
3
5
9
ArrayList:

 Java ArrayList class uses a dynamic array for storing the elements.
 It is like an array, but there is no size limit.
 We can add or remove elements anytime.
 So, it is much more flexible than the traditional array.
 The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of the List interface here.
 The ArrayList maintains the insertion order internally.
 We cannot create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases.
For example:
ArrayList<int> al = ArrayList<int>(); // does not work
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

Example:

import java.util.*;
public class ArrayListExample1
{
public static void main(String args[])
{
//Creating arraylist
ArrayList<String> list=new ArrayList<String>();
list.add("Mango"); //Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");

//Printing the arraylist object


System.out.println(list);
}
}

Output:
[Mango, Apple, Banana, Grapes]
HashSet:
 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only.
 HashSet allows null value.
 HashSet class is non-synchronized.
 HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
 HashSet is the best approach for search operations.

Example:
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

Output:
Five
One
Four
Two
Three
TreeSet:

 TreeSet class implements the Set interface that uses a tree for storage.
 It inherits Abstract Set class and implements the Navigable Set interface.
 The objects of the TreeSet class are stored in ascending order
 Java TreeSet class contains unique elements only like HashSet.
 Java TreeSet class access and retrieval times are quiet fast.
 Java TreeSet class doesn't allow null elements.
 The TreeSet can only allow those generic types that are comparable.

Example:
import java.util.*;
class TreeSet1
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

//Traversing elements
Iterator<String>itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output:
Ajay
Ravi
Vijay
Accessing a Collection via an iterator

Iterator Interface:

 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 java.util 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.
Step - 1: Create an object of the Iterator by calling collection.itertor( ) method.
Step - 2: Use the method hasNext( ) to access to check does the collection has the next
element. (Use a loop).
Step - 3: Use the method next( ) to access each element from the collection. (use inside
the loop).

Methods of Iterator interface:


 Iterator iterator( ) Used to obtain an iterator to the start of the collection.
 hasNext( ) Returns true if the collection has the next element, otherwise, it
returns false.
Example:

import java.util.*;
public class TreeSetExample
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
set.add(num.nextInt(100));

Iterator collection = set.iterator();


System.out.println("All the elements of TreeSet collection:");
while(collection.hasNext())
System.out.print(collection.next() + " ");
}

Output:
All the elements of TreeSet collection:
12 23 42 57 59 68 79 93 98

You might also like