Collection FrameWork-2
Collection FrameWork-2
Set
HashSet SortedSet
TreeSet
Hash Set
• The underlying data Structure is Hash Table.
• Duplicate values are not allowed .If we insert duplicate
values we don’t get any compile time or run time error,
add() returns false.
• Insertion order is not preserved and all objects are inserted
based on hash-code of objects.
• Heterogenous objects are allowed.
• “null” insertion is possible.
• It is best suitable for Search Operation.
Constructors of HashSet
• HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16.
and default fill ratio=0.75.
• HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with Specified initial capacity
and default fill ratio=0.75.
• HashSet h=new HashSet(int initialcapacity,float loadfactor);
Creates an empty HashSet object with Specified initial capacity
and specified loadfactor(fill ratio).
HashSet h=new HashSet(Collection c);
For inter conversion between collection Objects.
• Load Factor
After Loading the how much factor, a new HashSet Object will be
created that factor is called as Load Factor or Fill Factor
For Example:
If we consider an ArrayList Object then
ArrayList a=new ArrayList()- by default load factor is 0.5
• Example
import java.util.*;
Class HashSetDemo
{
psvm(String s[])
{
HashSet h=new HashSet();
h.add(“B”);
h.add(“D”);
h.add(“Z”);
h.add(null);
h.add(10);
s.o.pln(“Elements of HashSet”+h)
s.o.pln(h.add(“Z”));}}
• Other utility methods
• The HashSet class has the following methods to work with elements of it.
• int size( ) - Returns the total number of elements in the invoking HashSet.
• boolean isEmpty( ) - Returns true if the HashSet is empty otherwise returns false.
• HashSet clone( ) - Returns a copy of the invoking HashSet.
• boolean contains(Object element) - Returns true if the HashSet contains given element
otherwise returns false.
• boolean containsAll(Collection c) - Returns true if the HashSet contains given collection of
elements otherwise returns false.
• boolean equals(Object o) - Compares the specified object with invoking HashSet collection for
equality.
• int hashCode( ) - Returns the hash code of the invoking HashSet.
• Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from
invoking HashSet.
• Spliterator spliterator( ) - Creates spliterator over the elements in a HashSet.
• Iterator iterator( ) - Returns an iterator over the elements in the HashSet. The iterator does not
return the elements in any particular order.
• The HashSet class has the following methods to remove items.
• boolean remove(Object o) - Removes the specified element from the
invoking HashSet.
• boolean removeAll(Collection c) - Removes all the elements of
specified collection from the invoking HashSet.
• boolean removeIf(Predicate p) - Removes all of the elements of
HashSet collection that satisfy the given predicate.
• boolean retainAll(Collection c) - Removes all of the elements of
HashSet collection except specified collection of elements.
• void clear( ) - Removes all the elements from the HashSet.
Import java.util.*;
public class HashSetExample1 {
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
System.out.println("\nHashSet is\n" + set);
anotherSet.addAll(set);
}
System.out.println("\nanotherSet is\n" + anotherSet);
set.remove(20);
System.out.println("\nHashSet after remove(20) is\n" + set);
anotherSet.removeAll(set);
System.out.println("\nanotherSet after removeAll(set) is\n" + anotherSet);
set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" + set);
anotherSet.clear();
System.out.println("\nanotherSet after clear() is\n" + anotherSet);
}
SortedSet
• It is the child interface of set.
• If we want to represent a group of individual objects according to
some sorting order and duplicates are not allowed then we should
go for SortedSet.
For Example
{1,2,3}
{2,3,1} All the sets are equal but we cannot say which is the 1st or last.
{3,1,2}
For this these elements need tobe sorted.
SortedSet Specific Methods
Example Set: {100,101,103,104,107,110,115}
Object first()-returns first element of the SortedSet. 100
Object last()-returns last element of the SortedSet. 115
SortedSet headset(Object obj)-returns the SortedSet whose elements
are less than obj.
Ex:headSet(104)—[100,101,103]
SortedSet tailSet(Object obj)- returns the SortedSet whose elements
are greater than or equal obj.
Ex:tailSet(104)—[104,107,110,115]
SortedSet subSet(Object obj1,Object obj2)-returns the SortedSet
whose elements are >=obj1 and< obj2.
Ex:subSet(103,110)—[103,104,107]
Comparator comparator()-returns Comparator object that describes
underlying technique.If we are using default sorting order then
we will get null.
default sorting order---numbers Ascending Order
--- Strings Alphabetical order.
TreeSet
• The underlying datastructure for TreeSet is Balanced Tree.
• Duplicate objects are not allowed.
• Insertion order is not preserved,but all objects will be
inserted according to some sorting order.
• Heterogenous objects are not allowed.
• Null Insrtion is allowed but only once.
Constructors of TreeSet
TreeSet t=new TreeSet();
creates an empty TreeSet object where elements will be inserted
according default natural sorting order.
TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet Object where elements will be
inserted according to customized sorting order
TreeSet t=new TreeSet(SortedSet s);
Creates TreeSet on SortedSet of elements.
TreeSet t=new TreeSet(Collection C);
Converts any collection object to TreeSet.
Import java.util.*;
class TreeSetDemo {
psvm(String s[]) {
TreeSet t=new TreeSet();
t.add(“A”);
t.add(“a”);
t.add(“B”);
t.add(“Z”);
t.add(“L”);
t.add(new Integer(10));
t.add(null);
System.out.println(t);
}}
Note:
• Null can be inserted as the first element,but after inserting null if we
try to insert any other element we will get NullPointerException
For example:TreeSet t=new TreeSet();
t.add(null);
t.add(“a”);
For Non empty TreeSet if we are trying to insert Null then we will get
NullPointerException.
For example:TreeSet t=new TreeSet();
A
t.add(“a”);
t.add(null);
null
PriorityQueue
10 20 5 15 10
Consider an ArrayList
ArrayList a=new ArrayList()----- “a” is the object of ArrayList class.
Iterator i=a.iterator----stmt is used to traverse through ArrayList
Collection
Iterator supports 3 methods
• boolean hasNext()-returns true if iterator has more elements to
iterate.
• Object next():returns the next element in the collection until the
hasNext() method return true.This method throws “NoSuchElement
Exception if there is no next element.
• Void remove():removes the current element in the collection,this
method throws IllegalStateException if this function is called before
next() is invoked.
Example
import java.util.*;
class IteratorDemo {
public static void main(String s[]){
ArrayList a=new ArrayList();
a.add(10);
a.add(30);
a.add(50);
a.add(40);
a.add(20);
Iterator i=a.iterator();
System.out.println("Elements of ArrayList are:");
while(i.hasNext())
System.out.println(i.next()+" ");
}}
import java.util.*;
class IteratorDemo1 {
public static void main(String s[]) {
ArrayList a=new ArrayList();
for(int i=0;i<=10;i++)
a.add(i);
System.out.println(a);
Iterator i= a.iterator();
while(i.hasNext()) {
Integer I=(Integer)i.next();
if(I%2==0)
System.out.println(I);
else
i.remove(); }
System.out.println(a);
} }
Limitations of Iterator
can used to Access only in forward direction.
We can perform read or remove operations but we can’t
perform replacement of new objects.
ListIterator
• ListIterator we can move either to the forward direction or to
the backward direction and hence ListIterator is
bidirectional.
• Along with read and remove operation we can perform
replacement and addition of new objects.
We can create ListIterator Object by using listIterator()
method of List Interface.
public ListIterator listIterator()
Example
ListIterator li=l.listIterator();
where l is any List object.
Methods:
• ListIterator is the child interface of Iterator and all the
methods of iterator by default available to ListIterator.
• It defines the following nine methods
• To access elements in forward direction the methods are
public Boolean hasNext()
public void next()
public int nextIndex()
• To access elements in backward direction the methods are
public Boolean hasPrevious()
public void previous()
public int PreviousIndex()
• Other Methods
public void remove()
public void set(Object new)
public void add(Object new)
import java.util.*;
class ListIteratorDemo {
public static void main(String args[]) {
LinkedList l=new LinkedList();
l.add("a");
l.add("c");
l.add("z");
l.add("k");
System.out.println(l);
ListIterator lt=l.listIterator();
while(lt.hasNext()) {
String s=(String)lt.next();
if(s.equals("c"))
lt.remove();
else if(s.equals("z"))
lt.add("m");
else if(s.equals("k"))
lt.set("y"); }
For Each Alternative
• It is enhanced for loop.
• This concept is introduced from java1.5 version
• It is used to process the elements of array or Collections.
• We can iterate elements without bounds.
• It access elements from first index to last index.
• For each loop process elements one by one only in forward direction.
Syntax:
for(data_type variable:array|collection)
{
//body of foreach loop
}
import java.util.*;
class ForEachDemo
{
public static void main(String args[])
{
ArrayList<Integer> a=new ArrayList<Integer> ();
a.add(10);
a.add(20);
a.add(30);
a.add(40);
System.out.println(“Array elements are”);
for(Integer s:a)
System.out.println(s);
}}
Map Interface and Classes
Map
TreeMap
Map Interface and Classes
• Map is not a child Interface of Collection.
• If you want to represent a group of objects as Key-Value pair then we
use Map.
Ex: Key Value
101 sachin
102 rakesh
103 sriram
104 Sachin