Collection
Collection
Collections Framework
• Collection: It is used to that groups elements into an entity.
HashMap
LinkedHashMap
SortedMap
TreeMap
Collections Framework
Collection: Represents group of individual objects.
Methods:
boolean add(object o) void clear()
int indexOf(object o)
int LastIndexOf(object o)
Collections Framework
ArrayList : The ArrayList class implements the List interface.
It uses a dynamic array to store the duplicate element of different data types.
It preserves insertion order and is non-synchronized.
The ArrayList class elements can be randomly accessed.
Constructors
ArrayList arr = new ArrayList();
• It doesn’t contain any methods we have to use Collection Interface methods only.
Collections Framework
HashSet : HashSet extends AbstractSet and implements the Set interface.
It creates a collection that uses a hash table for storage.
Duplicates not allowed and insertion order not preservred.
Null insertion is possible only once.
A hash table stores information by using a mechanism called hashing.
In hashing, the informational content of a key is used to determine a unique value, called its
hash code.
HashSet implements serializable and clonable Interfaces.
Constructors
HashSet v = new HashSet ();
HashSet v = new HashSet (intialcapacity);
HashSet v = new HashSet (initialcapacity,fillratio );
HashSet v = new HashSet (Collection c);
Collections Framework
SortedSet: It is the child interface of Set interface. It inhibits a list type data structure in
which objects are stored in some sorted order and duplicate values are not allowed.
Methods
Object first()
Object last()
Comparator comparator()
SortedSet headSet(obj)
SortedSet tailSet(obj)
SortedSet subSet(obj,obj)
Collections Framework
TreeSet : TreeSet implements the SortedSet interface.
It creates a collection that uses a Balanced tree for storage.
Duplicates not allowed and insertion order not preservred.
Null insertion is possible only once.
Hetrogeneous Objects are not allowed.
TreeSet implements serializable and clonable Interfaces.
Constructors
TreeSet v = new TreeSet ();
TreeSet v = new TreeSet (Comparator c);
TreeSet v = new TreeSet (SortedSet s);
TreeSet v = new TreeSet (Collection c);
Collections Framework
Queue: It is the child interface of Collection interface.
It inhibits a list type data structure in which objects are stored in FIFO.
Methods
Object add(): Adds the element and returns true upon success.
Object Offer(Object): Adds the element to the queue.
Object remove(): It removes the head retrieve element.
Object pool(): It retrieves and removes the head of queue, or returns null if queue is empty.
Object peek(): retrieves the head element.
Collections Framework
PriorityQueue : The PriorityQueue class provides the facility of using queue.
Duplicates not allowed and insertion order not preservred.
Null insertion is not possible.
PriorityQueue implements serializable and clonable Interfaces.
Constructors
Constructors
LinkedHashMap():
Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor
(0.75).
Collections Framework
import java.util.*;
public class LinkedHashMapDemo
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
LinkedHashMap studinfo = new LinkedHashMap();
studinfo.put(501, "Durga");
studinfo.put(510, "Madhu");
studinfo.put(507, "Naveen");
studinfo.put(512, "Ramesh");
System.out.println("Student Information\n" + studinfo);
System.out.print("Enter Rollnumber: ");
int id = read.nextInt();
if(studinfo.containsKey(id))
{
System.out.println("Student Name - " + studinfo.get(id));
}
else
{
System.out.println("No Record Found");
}
}
}
Collections Framework
TreeMap : The TreeMap class is a child class of AbstractMap, and it implements the
NavigableMap interface which is a child interface of SortedMap.
It is used to store the data in the form of key, value pair using a red-black tree concepts.
Duplicate key not allowed and Values can be repeated.
Null keys and values not allowed.
follows the ascending oreder based on keys.
Constructors
TreeMap tm=new TreeMap();
Object put(Object key, Object value): Inserts a key and its value into the dictionary.
Returns null on success; returns the previous value associated with the key if the key is already exist.
Object remove(Object key): it returns the value associated with given key and removes the same; Returns null if the key does not exist.
Object get(Object key): It returns the value associated with given key; Returns null if the key does not exist.
boolean isEmpty( )It returns true if dictionary has no elements; otherwise returns false.
int size( )It returns the total number of elements in the dictionary.
import java.util.*;
Collections Framework
public class DictionaryDemo {
public static void main(String args[]) {
Dictionary dict = new Hashtable();
dict.put(501, "Durga");
dict.put(510, "Madhu");
dict.put(507, "Naveen");
dict.put(512, "Ramesh");
System.out.println("Dictionary\n=> " + dict);
System.out.println("\n\nValue associated with key 512 => " + dict.get(512));
System.out.println("\nDictionary has " + dict.size() + " elements");
System.out.println("\nIs Dictionary empty? " + dict.isEmpty());
System.out.print("\nKeys in Dictionary\n=> ");
Enumeration i = dict.keys();
while(i.hasMoreElements()) {
System.out.print(" " + i.nextElement());
}
System.out.print("\n\nValues in Dictionary\n=> ");
Enumeration i1 = dict.elements();
while(i1.hasMoreElements()) {
System.out.print(" " + i1.nextElement());
}}}
Collections Framework
Hashtable which works like a HashMap but it is synchronized.
The Hashtable is a concrete class of Dictionary.
It is used to store and manage elements in the form of a pair of key and value.
Constructors:
Hashtable( )It creates an empty hashtable with the default initial capacity 11.
Hashtable(int capacity)It creates an empty hashtable with the specified initial capacity.
Hashtable(int capacity, float loadFactor)It creates an empty hashtable with the specified initial capacity and loading
factor.
class HashtableDemo {
public static void main(String args[]) {
Hashtable ht = new Hashtable();
ht.put(501, "Durga");
ht.put(510, "Madhu");
ht.put(507, "Naveen");
ht.put(512, "Ramesh");
System.out.println("HashTable\n=> " + ht);
System.out.println("\n\nValue associated with key 512 => " + ht.get(512));
System.out.println("\nHashtable has " + ht.size() + " elements");
System.out.println("\nIs hashtable empty? " + ht.isEmpty());
}}
Collections Framework
Properties which is a child class of Hashtable class.
It implements interfaces like Map,
Implements Cloneable, and Serializable.
Properties class, we can load key, value pairs into a Properties object from a stream.
Properties class, we can save the Properties object to a stream.
Constructors:
Properties( )It creates an empty property list with no default values.
Properties(Properties defaults)It creates an empty property list with the specified defaults.
Methods
String getProperty(String key)It returns value associated with the specified key.
void setProperty(String key, String value)It calls the put method of Hashtable.
void store(OutputStream os, String comment)It writes the properties in the OutputStream object.
Collections Framework
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
File confFile = null;
try {
confFile = new File("studentfile.properties");
fos = new FileOutputStream(confFile);
Properties cp = new Properties();
cp.setProperty("Name1", "Durga");
cp.setProperty("Name2", "Madhu");
cp.store(fos, "Student Names");
fos.close();
System.out.println("Student data saved!!!");
}
catch(Exception e) {
System.out.println("Something went wrong while opening file");
}
}
}
Collections Framework
The StringTokenizer class in java used to break a string into tokens
Constructors:
StringTokenizer(String str)It creates StringTokenizer object for the specified string str with default delimeter.
StringTokenizer(String str, String delimeter)It creates StringTokenizer object for the specified string str with
specified delimeter.
StringTokenizer(String str, String delimeter, boolean returnValue)It creates StringTokenizer object with specified
string, delimeter and returnValue.
Methods
boolean hasMoreTokens():checks if there is more tokens available.
String nextToken()It returns the next token from the StringTokenizer object.
String nextToken(String delimeter)It returns the next token based on the delimeter.
boolean hasMoreElements()It returns true if there are more tokens object. otherwise returns false.
Object nextElement()It returns the next token from the StringTokenizer object.
Methods
long getTime()It returns the time represented by this date object.
void setTime(long time)It changes the current date and time to given time.
boolean after(Date date)It returns true, if the invoking date is after the argumented date.
int hashCode()It returns the hash code value of the invoking date object.
int compareTo(Date date)It compares current date with given date.
String toString()It converts this date into Instant object.
Collections Framework
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date time = new Date();
System.out.println("Current date : " + time);
System.out.println("Date : " + time.getTime() + " milliseconds");
System.out.println("hashCode : " + time.hashCode());
System.out.println("Date to String : " + time.toString());
}
}
Collections Framework
The Comparator is an interface available in the java.util package.
The java Comparator is used to order the objects of user-defined classes.
The java Comparator can compare two objects from two different classes.
Using the java Comparator, we can sort the elements based on data members of a class.
For example, we can sort based on roolNo, age, salary, marks, etc.
Methods
int compare(Object obj1, Object obj2): It is used to compares the obj1 with o bj2 .
boolean equals(Object obj): It is used to check the equity between current object and argumented object.
Collections Framework
import java.util.*;
class Student{
String name;
double percentage;
Collections.sort(studList, com);
Client-side