Unit 5
Unit 5
Unit 5
1. Collection Framework
• 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.
• What is Collection framework
o The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
▪ Interfaces and its implementations, i.e., classes
▪ Algorithm
o Hierarchy of Collection Framework:
Let us see the hierarchy of Collection framework. The java.util package contains
all the classes and interfaces for the Collection framework.
o Iterable Interface
▪ The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all
the subclasses of Collection interface also implement the Iterable
interface.
o 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
1
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
// Main class
public class Arrays1 {
Arrays.sort(intArr);
System.out.println(
intKey + " found at index = "
+ Arrays.binarySearch(intArr, intKey));
}
}
3. ArrayList class
• 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.
Ex.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
4. LinkedList class
• 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.
3
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Ex.
import java.util.LinkedList;
public class TestJavaCollection2
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();
al.add("Needa");
al.add("Hardik");
al.add("Jay");
al.add("Raj");
System.out.println("List:"+al);
al.add(1,"Ranjeet");
System.out.println("Updated list:");
System.out.println("List:"+al);
al.set(1, "Kajal");
System.out.println("Updated list:"+ al);
str = al.remove(1);
System.out.println("Removed member:"+str);
int i = al.indexOf("Needa");
System.out.println("index of:"+ "Needa:"+i);
if(al.contains("Needa"))
{
i = al.indexOf("Needa");
al.set(i,"Hirva");
System.out.printf("Updated:"+al);
}
4
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
}
}
Output:
List:[Needa, Hardik, Jay, Raj]
Updated list:
List:[Needa, Ranjeet, Hardik, Jay, Raj]
str:Ranjeet
Updated list:[Needa, Kajal, Hardik, Jay, Raj]
Removed member:Kajal
Linked list contains:true
Linked list contains:false
index of:Needa:0
Updated:[Hirva, Hardik, Jay, Raj]
5. ListIterator interface
• The ListIterator interface of the Java collections framework provides the functionality to
access elements of a list.
• It is bidirectional. This means it allows us to iterate elements of a list in both the direction.
• It extends the Iterator interface.
• Methods of ListIterator
o hasNext() - returns true if there exists an element in the list
o next() - returns the next element of the list
o nextIndex() returns the index of the element that the next() method will return
o previous() - returns the previous element of the list
o previousIndex() - returns the index of the element that the previous() method will
return
o remove() - removes the element returned by either next() or previous()
o set() - replaces the element returned by either next() or previous() with the
specified element
• Ex.
import java.util.ArrayList;
import java.util.ListIterator;
class TestJavaCollection3
{
public static void main(String[] args)
{
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList: " + numbers);
iterate = numbers.listIterator();
iterate.next();
iterate.next();
}
}
Output:
ArrayList: [1, 3, 2]
Next Element: 1
Position of Next Element: 1
Is there any next element? true
Previous Element: 3
Position of the Previous element: 0
6. HashSet class
• Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
• HashSet stores the elements by using a mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• 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.
6
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• Ex.
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Manthan");
set.add("Priyanshi");
set.add("Rushi");
set.add("Titiksha");
set.add("Manthan");
//Traversing elements
System.out.println("Hash set:"+set);
}
}
Output:
Hash set:[Manthan, Titiksha, Priyanshi, Rushi]
Ex.
import java.util.*;
class HashSet2{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ambika");
set.add("Chaitnya");
set.add("Jimeet");
set.add("Kushal");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Jimeet");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Karan");
set1.add("Madhu");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Kushal"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
7
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Output:
An initial list of elements: [Ambika, Chaitnya, Jimeet, Kushal]
After invoking remove(object) method: [Ambika, Chaitnya, Kushal]
Updated List: [Ambika, Chaitnya, Karan, Madhu, Kushal]
After invoking removeAll() method: [Ambika, Chaitnya, Kushal]
After invoking removeIf() method: [Ambika, Chaitnya]
After invoking clear() method: []
Ex.
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
8
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Output:
101 Let us C Yashwant Kanetkar BPB 8
103 Operating System Galvin Wiley 6
102 Data Communications & Networking Forouzan Mc Graw Hill 4
7. LinkedHashSet class
• Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.
• Java LinkedHashSet class contains unique elements only like HashSet.
• Java LinkedHashSet class provides all optional set operations and permits null elements.
• Java LinkedHashSet class is non-synchronized.
• Java LinkedHashSet class maintains insertion order.
Ex.
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("AB");
al.add("AC");
al.add("AB");
al.add("AD");
System.out.println("LinkedHashSet:"+al);
// Removing element
al.remove("AC");
System.out.println(" After removing LinkedHashSet:"+al);
// Add all
al.addAll(lhs);
System.out.println(" After adding LinkedHashSet:"+al);
//Intersection of Sets
al.clear();
al.add("A");
al.add("B");
lhs.add("A");
lhs.add("C");
9
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
al.retainAll(lhs);
System.out.println(" Intersection of Hashset"+al);
// Difference of Sets
al.clear();
al.add("A");
al.add("B");
lhs.add("A");
lhs.add("C");
al.removeAll(lhs);
System.out.println("Difference of Hashset"+al);
}
}
Output:
LinkedHashSet:[AB, AC, AD]
After removing LinkedHashSet:[AB, AD]
After adding LinkedHashSet:[AB, AD, Ajay, Vijay]
Intersection of Hashset[A]
Difference of Hashset[B]
8. TreeSet class
• Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet
class are stored in ascending order.
• TreeSet is being implemented using a binary search tree, which is self-balancing just like
a Red-Black Tree. Therefore, operations such as a search, remove, and add consume
O(log(N)) time.
• 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 element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
• The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.
10
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
EX.
import java.util.TreeSet;
import javax.swing.plaf.synth.SynthCheckBoxMenuItemUI;
class TreeSet1 {
public static void main(String[] args) {
//Remove Elements
// Using lower()
System.out.println("Using lower: " + numbers.lower(5));
// Using ceiling() Returns the lowest element among those elements that are greater
than the specified element
//If the element passed exists in a tree set, it returns the element passed as an
argument.
System.out.println("Using ceiling: " + numbers.ceiling(5));
// Using floor() Returns the greatest element among those elements that are less
than the specified element
//If the element passed exists in a tree set, it returns the element passed as an
argument.
System.out.println("Using floor: " + numbers.floor(5));
// Using pollLast()
System.out.println("Removed Last Element: " + numbers.pollLast());
9. Map interface
• The Map interface of the Java collections framework provides the functionality of the map
data structure.
• In Java, elements of Map are stored in key/value pairs. Keys are unique values associated
with individual Values.
• A map cannot contain duplicate keys. And, each key is associated with a single value.
13
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• We can access and modify values using the keys associated with them.
• In the above diagram, we have values: United States, Brazil, and Spain. And we have
corresponding keys: us, br, and es.
• Since Map is an interface, we cannot create objects from it.
• In order to use functionalities of the Map interface, we can use these classes: HashMap,
EnumMap, LinkedHashMap, WeakHashMap, TreeMap.
14
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Ex.
import java.util.Map;
import java.util.HashMap;
class HashMap1 {
15
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Ex.
import java.util.TreeMap;
class TreeMap1 {
public static void main(String[] args) {
// Creating TreeMap of even numbers
TreeMap<String, Integer> evenNumbers = new TreeMap<>();
// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
System.out.println("TreeMap of even numbers: " + evenNumbers);
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("TreeMap of numbers: " + numbers);
// Using keySet()
System.out.println("Keys: " + numbers.keySet());
// Using values()
System.out.println("Values: " + numbers.values());
// get() - Returns the value associated with the specified key. Returns null if the key
is not found.
// Using get()
numbers.put("Three", 3);
16
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
//getOrDefault() - Returns the value associated with the specified key. Returns the
specified default value if the key is not found.
// Using getOrDefault()
int value2 = numbers.getOrDefault("Five", 5); // Try with key:"Three"
System.out.println("Using getOrDefault(): " + value2);
}
}
Output:
TreeMap of even numbers: {Four=4, Six=6, Two=2}
TreeMap of numbers: {Four=4, One=1, Six=6, Two=2}
Key/Value mappings: [Four=4, One=1, Six=6, Two=2]
Keys: [Four, One, Six, Two]
Values: [4, 1, 6, 2]
Using get(): 3
Using getOrDefault(): 5
Removed value: 2
Is the entry {Three=3} removed? true
Updated TreeMap: {Four=4, One=1, Six=6}
17
Subject: Programming with Java (102044502)
Unit 5: Collection API
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Ex.
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
}
}
18