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

Collection_framework_Java_By_Kunal_sir

The document provides an overview of the Java Collection Framework, detailing its architecture, interfaces, and classes such as List, Set, and their implementations like ArrayList, LinkedList, and HashSet. It explains important methods of the Collection interface and Iterator interface, along with examples of using these classes. Additionally, it compares ArrayList and LinkedList, highlighting their differences in storage and manipulation efficiency.
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)
2 views

Collection_framework_Java_By_Kunal_sir

The document provides an overview of the Java Collection Framework, detailing its architecture, interfaces, and classes such as List, Set, and their implementations like ArrayList, LinkedList, and HashSet. It explains important methods of the Collection interface and Iterator interface, along with examples of using these classes. Additionally, it compares ArrayList and LinkedList, highlighting their differences in storage and manipulation efficiency.
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

By Kunal Sir

Collection framework

What is a framework in Java?


 It provides ready made architecture
 It represents a set of classes and interfaces

What is Collection framework?


 The Collection framework represents a unified architecture for storing and
manipulating a group of objects.
 The java.util package contains all the classes and interfaces

Important Methods ofCollection interface


1. Public Boolean add(objecto):Itisusedto insert an element in this
collection
2. Public Iterator iterator():It returns an iterator.
3. Public Object get(index x):this methods return the object of index
position

Iterator interface
Iterator interface provides the facility of iterating the elements.
1. Public Boolean hasNext():It returns true if the iterator hasmore
elements otherwise it returns false.
2. public Object next(): It returns the element and moves the cursor
pointer to thenext element.

The following are the interfaces present in the framework .


1. Iterable Interface:

This is the root interface for the entire collection framework. The
collection interface extends the iterable interface. Therefore, inherently,
all the interfaces and classes implement this interface. The main
functionality of this interface is to provide an iterator for the collections.
Therefore, this interface contains only one abstract method which is the
iterator. It returns the
Iterator iterator();

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

2. Collection Interface:
This interface extends the iterable interface and is implemented by all
the classes in the collection framework. This interface contains all the
basic methods which every collection has like adding the data into the
collection, removing the data, clearing the data, etc. All these methods are
implemented in this interface because these methods are implemented by
all the classes irrespective of their style of implementation. And also,
having these methods in this interface ensures that the names of the
methods are universal for all the collections. Therefore, in short, we can
say that this interface builds a foundation on which the collection classes
are implemented.

3. List Interface:
This is a child interface of the collection interface. This interface is
dedicated to the data of the list type in which we can store all the ordered
collection of the objects. This also allows duplicate data to be present in it.
This list interface is implemented by various classes
like ArrayList, LinkedList,Vector etc. Since all the subclasses implement
the list, we can instantiate a list object with any of these classes. For
example,

List <T> al = new ArrayList<> ();


List <T>ll = new LinkedList<> ();
List <T> v = new Vector<> ();

Where T is the type of the object


The classes which implement the List interface are as follows:
A. ArrayList:
ArrayList provides us with dynamic arrays in Java. Though, it may be
slower than standard arrays but can be helpful in programs where lots of
manipulation in the array is needed. The size of an ArrayList is increased
automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list.
ArrayListcan not be used for primitive types, like int, char, etc. We will
need a wrapper class for such cases. Let’s understand the ArrayList with
the following example:

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

import java.util.*;
public class Test {
public static void main(String args[])
{
List list=new ArrayList();
//Adding object in arraylist
list.add(10);
list.add(20);
list.add(30);
list.add(10);

System.out.println(list);//[10,20,30,10]
Iterator itr=list.iterator();
while(itr.hasNext())
{
intx=(int)itr.next();
System.out.println(x);
}
//Using Stream Api
list.stream().forEach(i->{
System.out.print(i+" ");
});
}
}
B. LinkedList:
Linked List class is an implementation of the LinkedList data
structure which is a linear data structure where the elements are not
stored in contiguous locations and every element is a separate object with
a data part and address part. The elements are linked using pointers and
addresses. Each element is known as a node. Let’s understand the
LinkedList with the following example:

import java.util.*;

public class Test {

public static void main(String[] args)


{
LinkedList<Integer>list= newLinkedList<Integer>();
for(int i = 1; i<= 5; i++)
{
list.add(i);
}
// Printing elements
System.out.println(list);

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

Iterator itr=list.iterator();
while(itr.hasNext())
{
int x=(int)itr.next();
System.out.println(x);
}
//Using Stream Api
list.stream().forEach(i->{
System.out.print(i+" ");
});

}
}
Output:
1
2
3
4
5
C. Vector:
A vector provides us with dynamic arrays in Java. Though, it may be
slower than standard arrays but can be helpful in programs where
lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary
difference between a vector and an ArrayList is that a Vector is
synchronized and an ArrayList is non-synchronized. Let’s understand
the Vector with an example:
import java.io.*;
import java.util.*;
public class Test{
// Main Method
public static void main(String[] args)
{
// Declaring the Vector
Vector<Integer> list = newVector<Integer>();
// Appending new elements at
// the end of the list
for(inti = 1; i<= 5; i++)
{
list.add(i);
}
// Printing elements
System.out.println(list);
Iterator itr=list.iterator();
while(itr.hasNext())

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

{
int x=(int)itr.next();
System.out.println(x);
}
}
}

Task 1:
import java.util.*;

public class Demo {


public static void main(String args[]) {
List<String>mh = newArrayList<>();
mh.add("pune");
mh.add("munbai");
List<String>jh = newArrayList<>();
jh.add("rachi");
jh.add("lohardaga");
List<List<String>>india = newArrayList<List<String>>();
india.add(mh);
india.add(jh);
System.out.println("using iterator");
Iterator<List<String>>itr = india.iterator();
while (itr.hasNext()) {
List<String>states = itr.next();
Iterator<String>itr1 = states.iterator();
while (itr1.hasNext()) {
String city = itr1.next();
System.out.println(city);
}
}
System.out.println("using for loop");
for (List<String>states :india) {
for (String city :states) {
System.out.println(city);
}
}
//using Stream APi
System.out.println("using Stream APi");
india.stream().forEach(states ->{

states.stream().forEach(city->{
System.out.println(city);

});
});

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

}
}
Task 2:

import java.util.*;

public class Demo {


public static void main(String args[])
{
List<String>mh=newArrayList<>();
mh.add("pune");
mh.add("munbai");

List<String>jh=newArrayList<>();
jh.add("rachi");
jh.add("lohardaga");

List<List<String>>india=newArrayList<List<String>>();
india.add(mh);
india.add(jh);

List<String> state1=newArrayList<>();
state1.add(" city 1");
state1.add(" city 2");
List<String> state2=newArrayList<>();
state2.add("rachi");
state2.add("lohardaga");

List<List<String>>usa=newArrayList<List<String>>();
usa.add(state1);
usa.add(state2);
List<List<List<String>>> word=newArrayList<List<List<String>>>();
word.add(india);
word.add(usa);

System.out.println("using iterator");
Iterator<List<List<String>>>itr= word.iterator();
while(itr.hasNext())
{
List<List<String>> list =itr.next();
Iterator<List<String>> itr1=list.iterator();
while(itr1.hasNext())
{
List<String>st= itr1.next();
Iterator<String> itr2=st.iterator();
while(itr2.hasNext())
{

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

String city= itr2.next();


System.out.println(city);
}
}
}
System.out.println("using for loop");
for(List<List<String>>list:word)
{
for(List<String>states:list)
{
for(String city:states)
{
System.out.println(city);
}
}
}
System.out.println("by Using Stream API");
word.stream().forEach(i ->{
i.stream().forEach(states ->{
states.stream().forEach(city ->
{
System.out.println(city);
});
});
});
}
}
4. SetInterface
A set is an unordered collection of objects in which duplicate values
cannot be stored. This collection is used when we wish to avoid the
duplication of the objects and wish to store only the unique objects. This
set interface is implemented by various classes
like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses
implement the set, we can instantiate a set object with any of these
classes. For example,
Set<T>hs = new HashSet<> ();
Set<T>lhs = new LinkedHashSet<> ();
Set<T>ts = new TreeSet<> ();
Where T is the type of the object.
The following are the classes that implement the Set interface:
A. HashSet:

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

The HashSet class is an inherent implementation of the hash table


data structure. The objects that we insert into the HashSet do not
guarantee to be inserted in the same order. The objects are inserted
based on their hashcode. This class also allows the insertion of NULL
elements. Let’s understand HashSet with an example:
import java.util.*;

public class HashSetDemo {

// Main Method
Public static void main(String args[])
{
// Creating HashSet and
// adding elements
HashSet<String>hs = newHashSet<String>();

hs.add("abc");
hs.add("pqr");
hs.add("mno");
hs.add("xyz");

Iterator<String>itr = hs.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output:
abc
mno
pqr
xyz

B. LinkedHashSet:
A LinkedHashSet is very similar to a HashSet. The difference is that this
uses a doubly linked list to store the data and retains the ordering of
the elements. Let’s understand the LinkedHashSet with an example:

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

import java.util.*;

public class LinkedHashSetDemo {

// Main Method
public static void main(String args[])
{
// Creating LinkedHashSet and

LinkedHashSet<String>lhs =newLinkedHashSet<String>();
// adding elements
lhs.add("abc");
lhs.add("mno");
lhs.add("pqr");
lhs.add("xyz");

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

Output:
abc
xyz
mno
pqr

C. Sorted Set Interface:


This interface is very similar to the set interface. The only difference is
that this interface has extra methods that maintain the ordering of the
elements. The sorted set interface extends the set interface and is used
to handle the data which needs to be sorted. The class which
implements this interface is TreeSet. Since this class implements the
SortedSet, we can instantiate a SortedSet object with this class. For
example,
SortedSet<T>ts = new TreeSet<> ();

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

Where T is the type of the object.


The class which implements the sorted set interface is TreeSet.

TreeSet:
The TreeSet class uses a Tree for storage. The ordering of the elements is
maintained by a set using their natural ordering whether or not an explicit
comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface. It can also be ordered by a
Comparator provided at set creation time, depending on which
constructor is used. Let’s understand TreeSet with an example:

import java.util.*;

public class TreeSetDemo


// Main Method
public static void main(String args[])
{
// Creating TreeSet and
// adding elements
TreeSet<String>ts = new TreeSet<String>();
ts.add("Abc");
ts.add("xyz");
ts.add("pqr");
ts.add("mno");

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

Output:
abc
mno
pqr
xyz

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly


array to store the elements. linked list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses an array. is faster than ArrayList because it uses
If any element is removed from the array, a doubly linked list, so no bit shifting is
all the other elements are shifted in required in memory.
memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for


accessing data. manipulating data.

5) The memory location for the elements The location for the elements of a
of an ArrayList is contiguous. linked list is not contagious.

6) Generally, when an ArrayList is There is no case of default capacity in a


initialized, a default capacity of 10 is LinkedList. In LinkedList, an empty list
assigned to the ArrayList. is created when a LinkedList is
initialized.

7) To be precise, an ArrayList is a resizable LinkedList implements the doubly


array. linked list of the list interface.

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of Vector increments 100% means doubles the


current array size if the number array size if the total number of elements exceeds
of elements exceeds from its than its capacity.
capacity.

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

3) ArrayList is not a legacy class. Vector is a legacy class.


It is introduced in JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized, i.e., in a


non-synchronized. multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.

5) ArrayList uses A Vector can use the Iterator interface


the Iterator interface to traverse or Enumeration interface to traverse the
the elements. elements.

List Set

1) The list implementation allows The set implementation doesn't allow us to


us to add the same or duplicate add the same or duplicate elements.
elements.

2)The insertion order is maintained It doesn't maintain the insertion order of


by the List. elements.

3)List allows us to add any number Set allows us to add at least one null value
of null values. in it.

4)The List implementation classes The Set implementation classes are


are LinkedList and ArrayList. TreeSet, HashSet and LinkedHashSet.

5)We can get the element of a We cannot find the element from the Set
specified index from the list using based on the index because it doesn't
the get() method. provide any get method().

6)It is used when we want to It is used when we want to design a


frequently access the elements by collection of distinct elements.
using the index.

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

7)The method of List interface The iterator is used when we need to


listiterator() is used to iterate the iterate the Set elements.
List elements.

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,
collection on the basis of a single element we can sort the collection on the
such as id, name, and price. basis of multiple elements such as id,
name, and price etc.

2) Comparable affects the original class, i.e., Comparator doesn't affect the
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 java.lang package. the java.util package.

5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.
Comparable Program :
package comparable;
public class Student implements Comparable<Student> {
private int rollno;
private String name;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

}
publicvoidsetName(String name) {
this.name = name;
}
@Override
public int compare To(Student stu) {
// sort by rollno
// return this.rollno=stu.rollno;
// sort by name
Return this.name.compareTo(stu.name);
}
}

Package comparable;
import java.util.*;

public class Test {


public static void main(String[] args) {
Student s1=newStudent();
s1.setRollno(2);
s1.setName("Xyz");

Student s2=newStudent();
s2.setRollno(3);
s2.setName("Pqr");
Student s=newStudent();
s.setRollno(2);
s.setName("Abc");

Set<Student> set=newTreeSet<>();
set.add(s);
set.add(s1);
set.add(s2);

for(Studentstu:set)
{
System.out.println(stu.getName());
System.out.println(stu.getRollno());
}
}
}

Comparator Program
public class Student {

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

private int rollno;


private String name;
public int getRollno() {
return rollno;
}
public void set Rollno(introllno) {
this.rollno = rollno;
}
public String getName() {
returnname;
}
public void setName(String name) {
this.name = name;
}

import java.util.Comparator;

public class SortByRollno implements Comparator<Student> {

@Override
public int compare(Student stu1, Student stu2) {
// TODO Auto-generated method stub
returnstu1.getRollno()-stu2.getRollno();
}
}

import java.util.Comparator;

public class SortByName implements Comparator<Student> {

@Override
public int compare(Student stu1, Student stu2) {
// TODO Auto-generated method stub
return stu1.getName().compareTo(stu2.getName());
}

}
import java.util.*;

public class Test {


public static void main(String[] args) {

Student s1 = newStudent();
s1.setRollno(1);

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

s1.setName("Xyz");

Student s2 = new Student();


s2.setRollno(3);
s2.setName("Pqr");
Student s = new Student();
s.setRollno(2);
s.setName("Abc");

System.out.println("enter your choice");


System.out.println("1. Sort By Name");
System.out.println("2. Sort By Rollno");

Set<Student>set = null;
Scanner sc = new Scanner(System.in);
Int ch = sc.nextInt();
if (ch == 1) {
set = new TreeSet<>(newSortByName());
}
elseif (ch == 2) {
set = new TreeSet<Student>(newSortByRollno());
}
set.add(s);
set.add(s1);
set.add(s2);

for (Studentstu :set) {


System.out.println(stu.getName());
System.out.println(stu.getRollno());
}
}
}

5. Map Interface
The map interface is present in java.util package represents a
mapping between a key and a value. The Map interface is not a subtype of
the Collection interface. Therefore it behaves a bit differently from the rest
of the collection types. A map contains unique keys.
Maps are perfect to use for key-value association mapping such as
dictionaries. The maps are used to perform lookups by keys or when
someone wants to retrieve and update elements by keys. Some common
scenarios are as follows:
A map of error codes and their descriptions.
A map of zip codes and cities.

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

A map of managers and employees. Each manager (key) is associated with


a list of employees (value) he manages.
A map of classes and students. Each class (key) is associated with a list of
students (value).
Characteristics of a Map Interface
1. A Map cannot contain duplicate keys and each key can map to at most one
value. Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
A map is a data structure that supports the key-value pair mapping for the
data. This interface doesn’t support duplicate keys because the same key
cannot have multiple mappings. A map is useful if there is data and we
wish to perform operations on the basis of the key. This map interface is
implemented by various classes like HashMap, TreeMap, etc. Since all the
subclasses implement the map, we can instantiate a map object with any
of these classes. For example,

Map<T> hm = new HashMap<> ();


Map<T> tm = new TreeMap<> ();

Where T is the type of the object.


The frequently used implementation of a Map interface is a HashMap.
HashMap:
HashMap provides the basic implementation of the Map interface of Java.
It stores the data in (Key, Value) pairs. To access a value in a HashMap, we
must know its key. HashMap uses a technique called Hashing. Hashing is a
technique of converting a large String to a small String that represents the
same String so that the indexing and search operations are faster. HashSet
also uses HashMap internally. Let’s understand the HashMap with an
example:
import java.util.*;

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

public class HashMapDemo {


// Main Method
public static void main(String args[])
{ // Creating HashMap and
// adding elements
HashMap<Integer, String>hm = new HashMap<Integer,String>();
hm.put(1, "java");
hm.put(2, "C");
hm.put(3, "C++");

// Finding the value for a key


System.out.println("Value for 1 is "+ hm.get(1));
// Traversing through the HashMap
for(Map.Entry<Integer, String>e :hm.entrySet())
{
System.out.println(e.getKey() + " "+ e.getValue());
}
System.out.println("Using foreach in Java 8");
hm.forEach((id, name) -> {
System.out.println("Key : " + id + " value : " + name);
});

System.out.println("usinn Stream API");


hm.entrySet().stream().forEach(e ->
System.out.println("Key : " + e.getKey() + " value : " +
e.getValue()));
for (Integer key :hm.keySet()) {
System.out.println("Key : " + key + " value : " +
hm.get(key));
}
System.out.println("by using Iterator");
Set<Integer>keys=hm.keySet();
Iterator<Integer>iterator =keys.iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
System.out.println("Key : " + key + " value : "
+hm.get(key));
}
}
}

Output:

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732
By Kunal Sir

Value for 1 is java


1 java
2 C
3 C++
Using foreach in Java 8
Key : 1 value : java
Key : 2 value : C
Key : 3 value : C++

Key : 1 value : java


Key : 2 value : C
Key : 3 value : C++
Key : 1 value : java
Key : 2 value : C
Key : 3 value : C++

by using Iterator
Key : 1 value : java
Key : 2 value : C
Key : 3 value : C++

1st Floor, Abov e Rupam Sweets, Priyanka Collections Building, Near Karv enagar Stop,
Karv enagar, Pune-52.Call:+91 8888022204.+91 7066970732

You might also like