collectionframework

java.util
Java Utility package is one of the most commonly used packages in the java applications
Java.util consist of

1]date and time facilities
2]internationalization
3]utility classes
such as StringtTokenizer,Random and BitArray
4]collection framework
5]legacy collection classes.

Date :
it is class from java.util package which represents system date and time.
//printing date and time
import java.util.*;
class DateDemo
{
public static void main(String[] args)
{
Date d= new Date();
System.out.println(d);//d.toString()

String s1=d.toString();
System.out.println(s1);
System.out.println(s1.substring(11,19));
}
}
—————————————————————————
Calendar
it is a abstract class from java.util to extract year,month,day,hour, minute,and second etc
Calendar c= new Calendar();//CTE
Calendar cal=Calendar.getInstance();
//printing day, hour etc using Calendar class.
import java.util.*;
class CalendarDemo
{
public static void main(String agrs[ ] )
{
Calendar cal=Calendar.getInstance( ) ;
System.out.println(cal.get(Calendar.YEAR));//prints 2019
System.out.println( cal.get( Calendar.HOUR));//11:43 PM
System.out.println( cal.get( Calendar.HOUR_OF_DAY));//:23:43 PM
System.out.println( cal.get( Calendar.MINUTE));//43
}
}
——————————————————————————-
java.text

Provides classes and interfaces for handling text,dates,numbers, and messages in language independent.
Format
DateFormat
NumberFormat

DateFormat:
it is class from java.text package to display the date and time in different styles.
DateFormat fmt=DateFormat.getDateTimeInstance();

Internationalization(i18n)
it is the process of designing an application so that it can be adapted to various languages and regions without changes.
it is abbreviated as i18n, because there are 18 letters between the first “i” and the last “n.”

Localization(l10N)
it is the process of adapting software for a specific region or language by adding locale-specific components and translating text.it is abbreviated as l10n, because there are 10 letters between the “l” and the “n.”

The primary task of localization is translating the user interface elements and documentation.

in java we can achieve Internationalization by using Locale class and properties file

Locale is a class from java.util package which represents a specific geographical, political, or cultural region.

it contains country code and language codes
Locale l= new Locale(String language, String country)
ex]Locale l=new Locale(“en”,”US”);

import java.util.*;
import java.text.*;
class FormatDemo
{
public static void main(String args[])
{
Date d=new Date();
DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.LONG,Locale.US);
String s=fmt.format(d);
System.out.println(s);
}
}
—————————————————————————————
utility classes:
Random
it is class from java.util package to generate a random number.
import java.util.*;
class RandomDemo
{
public static void main(String[] args)
{
Random r= new Random();
System.out.println(r.nextInt());
System.out.println(r.nextInt(5));//between 0 and 5
System.out.println(r.nextFloat());
System.out.println(r.nextDouble());
System.out.println(r.nextBoolean());
System.out.println((int)(Math.random()*1000));//between 0.0 and 1.0
}
}
—————————————————————————————-
StringTokenizer
it is a class from java.util package to break the String into tokens.

methods :
int countTokens()
boolean hasMoreElements()
boolean hasMoreTokens()
Object nextElement()
String nextToken()
String nextToken(String delim)

import java.util.*;
public class TokenDemo {
public static void main(String [] args) {
String str = “config software solutions”;

StringTokenizer tk = new StringTokenizer(str);
System.out.println(tk.countTokens());

while (tk.hasMoreTokens())
System.out.println(tk.nextToken());
}
}
—————————————————————————–
Scanner:
it is a class from java.util package introduced in 1.5 version.
it is used to read the data from file or keyboard.
import java.util.Scanner;
public class ScanDemo
{
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.println(“enter name”);
String name =sn.next();
System.out.println(“enter age”);
int age =sn.nextInt();
System.out.println(“name is”+name);
System.out.println(“age is”+age);
}
}

========collection framework==================
to store a group of elements or group of similar type of objects we are having array

1]Arrays are fixed in size ie once we create an array object there is no chance of increasing or decreasing size.
2]Arrays can hold only homogeneous elements.
3]adding the objects is easy at the end but inserting and deleting in the middle is difficult.

to avoid these problems java introduces collection frame work.
A collection frame work is a class library to handle group of objects .
collection frame work is implemented in java.util package.
A collection object or a container object is an object which can store a group of objects as single entity.

collection objects cannot store primitives(byte,short,int,float…) directly.

from java1.5 version onwards we can store primitives directly since primitives are converted into objects automatically using autoboxing.

diagram1:

Collection is an interface which can be used for representing a group of individual objects as single entity and it acts as root interface of collection frame work.

methods of Collection interface are:
boolean add(Object o);
boolean addAll(Collection c);
boolean remove(Object o);
boolean removeAll(Collection c);
boolean retainAll(Collection c);
void clear();
boolean contains(Object o);
boolean containsAll(Collection c);
boolean isEmpty();
int size();
Object[] toArray();
Iterator iterator();

Collections
it is an utility class to define several utility methods for Collection implemented class objects.

to retrieve the elements from the collection object by using
1)for each loop
2)Enumeration
3)Iterator interface
4)ListIterator interface

1)for- each loop
2)Enumeration
1.It is legacy interface introduced in 1.0 version
2.it is applicable only for legacy classes
3.While iterating the elements we are not allowed to remove the objects and we can perform only read operation
4.By using elements() method we can get Enumeration object
1.boolean hasMoreElements();
2.Object nextElement();
legacy classes and interfaces present in Collections framework(1.0 version)
Enumeration —Interface
Dictonary —–Abstract class
Hashtable —–Concrete class
Properties —–Concrete class
Vector —–Concrete class
Stack —–Concrete class
3)Iterator
Iterator
1 It is in 1.2 version
2. it is applicable for any Collection implemented class object.
3While iterating we can perform removal also in addition to read operation.
4.By using iterator() method we can get Iterator object

boolean hasNext()
Object next();
void remove()
3)ListIterator:
List Iterator:
it is the child interface of Iterator.
it is applied only for list implemented classes(ArrayList,LinkedList,Vector,Stack).
it is a bidirectional cursor ie we can move either to forward or backward direction
we can perform read,remove,add and replace operations.
public boolean hasNext();
public Object next();
public int nextIndex();
public boolean hasPrevious();
public Object previous();
public int previousIndex();
public void remove();
public void set(Object new)
public void add(Object new)

=====================================

Set:
it is a child interface of Collection interface.
it can be used to represent a group of individual objects as a single entity.
Duplicate objects are not allowed.
Insertion order is not preserved.
————————————————————
HashSet class
it is introduced in 1.2 version
it is implementation class for Set interface
heterogeneous objects are allowed
duplicates are not allowed
HashSet class implements Serializable and Cloneable
underlying data structure is Hashtable
null values are accepted only once
insertion order is based on hashcode of the object hence insertion order is not preserved

import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(new Integer(10));//in 1.4
hs.add(7);
hs.add(20);
hs.add(20);
hs.add(null);
hs.add(null);
System.out.println(“hash set values are “+hs);//hs.toString()

System.out.println(“using iterator”);
Iterator<Integer> it=hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println(“size is “+hs.size());//4
hs.remove(10);
System.out.println(“hash set values are “+hs);
System.out.println(“——————“);
hs.clear();
System.out.println(“hash set values are”+hs);
}//main
}//close

/*
using generics
—————-
HashSet<Integer> hs= new HashSet<Integer>(5);
HashSet<Student> hs= new HashSet<Student>();
HashSet<Customer> hs= new HashSet<Customer>();

*/
====================================================
LinkedHashSet(1.4)
It is the child class of HashSet.
In the case of HashSet insertion order is not preserved , but in the case of LinkedHashSet insertion will be preserved.

import java.util.*;
class LHSDemo
{
public static void main(String[] args)
{
LinkedHashSet<Integer> lhs=new LinkedHashSet<>();
lhs.add(10);
lhs.add(7);
lhs.add(20);
lhs.add(null);
System.out.println(lhs);//lhs.toString()
System.out.println(“using iterator”);
Iterator<Integer> it=lhs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

}//main
}//close
===================================================
SortedSet
it is child interface of Set interface.
it can be used to represent a group of individual objects in to a single entity.
All the objects are arranged in some sorting order(default ascending order)
Duplicates are not allowed.
======================================================
NavigableSet
It is introduced in 1.6 version
It is child interface of SortedSet and provides several utility methods for navigation purpose.
It doesn’t allows duplicates
Insertion order is preserved

=======================================================
TreeSet
It is Collection object which can be used to represent a group of objects according to some sorting order.
underlying datastructure is Balanced tree
Duplicates are not allowed
TreeSet is the implementation class for SortedSet and NavigableSet
All objects are stored according to some sorting order hence insertion order is not preserved
•Heterogeneous objects are not allowed violation leads to ClassCastException
For an Empty TreeSet as first element null value can be inserted but after inserting that first value if we are trying to insert any other objects then we will get NullPointerException
For an non empty TreeSet if we are trying to insert null value at run time you will get NullPointerException
SortedSet s= new Treeset();
NavigableSet ns=new Treeset();

import java.util.NavigableSet;
import java.util.TreeSet;
public class NavigableDemo
{
public static void main(String[] args)
{
NavigableSet<Integer> ns = new TreeSet<>();
ns.add(0);
ns.add(1);
ns.add(2);
ns.add(3);
ns.add(4);
ns.add(5);
ns.add(6);

// Get a reverse view of the navigable set
NavigableSet<Integer> reverseNs = ns.descendingSet();

// Print the normal and reverse views
System.out.println(“Normal order: ” + ns);
System.out.println(“Reverse order: ” + reverseNs);

NavigableSet<Integer> threeOrMore = ns.tailSet(3, true);
System.out.println(“3 or more: ” + threeOrMore);
System.out.println(“lower(3): ” + ns.lower(3));
System.out.println(“floor(3): ” + ns.floor(3));
System.out.println(“higher(3): ” + ns.higher(3));
System.out.println(“ceiling(3): ” + ns.ceiling(3));

System.out.println(“pollFirst(): ” + ns.pollFirst());
System.out.println(“Navigable Set: ” + ns);

System.out.println(“pollLast(): ” + ns.pollLast());
System.out.println(“Navigable Set: ” + ns);

System.out.println(“pollFirst(): ” + ns.pollFirst());
System.out.println(“Navigable Set: ” + ns);

System.out.println(“pollFirst(): ” + ns.pollFirst());
System.out.println(“Navigable Set: ” + ns);

System.out.println(“pollFirst(): ” + ns.pollFirst());
System.out.println(“Navigable Set: ” + ns);

System.out.println(“pollFirst(): ” + ns.pollFirst());
System.out.println(“pollLast(): ” + ns.pollLast());
}
}

=======================================

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet<String> ts=new TreeSet<>();
ts.add(“java”);
ts.add(“bigdata”);
ts.add(“oracle”);
ts.add(“sap”);
System.out.println(ts);
//ts.add(new Integer(10)); class cast exception

}
}

============================================

List

diagram:

it is the child interface of Collection.
It represents a group of individual objects as a single entity.
Duplicate objects are allowed and we can differentiate duplicate objects by using indexes.
Insertion order is preserved via indexes
Lsit interface is implemented by ArrayList ,LinkedList ,Vector and Stack.

methods of List
===============
1.boolean add(Object obj)
2.boolean add(int index,Object o)
3.boolean addAll(Collection c)
4.boolean addAll(int index,Collection c)
5.boolean remove(object o)
6.boolean removeAll(Collection c)
7.int indexOf(Object o)
8.int lastIndexOf(Objetc o)
9.Object get(int index)
10.Object set(int index , Object o)
11.ListIterator listIterator()
12.Object remove(int index)

==========================================
Stack Class:
It is the child class of Vector
it is LIFO(last in first out)

1.Object push (Object obj)
2.Object pop()
3.Object peek()
4.boolean empty()
5.int search(Object o)

import java.util.*;
class StackDemo
{
public static void main(String arg[])
{
Stack s=new Stack();
s.push(“a”);
s.push(“b”);
s.push(“c”);
System.out.println(s.search(“a”));// 3
System.out.println(s.search(“b”));//2
System.out.println(s.search(“c”));//1
System.out.println(s.search(“d”));//-1

System.out.println(s); // [a,b,c]
System.out.println(s.pop());
System.out.println(s); // [a,b]
System.out.println(s.peek());
System.out.println(s); // [a,b]
System.out.println(s.empty());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.empty());
//System.out.println(s.search(“a”)); // 3
}
}
=============================================
LinkedList
it is the implementation class for List.
Hetrogeneous objects are also allowed.
Duplicate objects are allowed.
Insersion order is preserved.
Null insertion is possible any number of times.
It implements serializable,clonable interfaces
LinkedList is the best choice if your frequent operation is insertion or deletion in the middle.

LinkedList methods
1.void addFirst(Object o)
2.void addLast(Object o)
3.Object removeFirst()
4.Object removeLast()
5.Object getFirst()
6.Object getLast()

import java.util.*;
class LinkedListDemo
{
public static void main(String arg[])
{
LinkedList l=new LinkedList();
l.add(“hello”);
l.add(new Integer(10));
l.add(null);
l.add(“hi”);
l.add(0,”scjp”);
l.add(“java”);
l.removeLast();
l.addFirst(“config”);
System.out.println(l);
}
}
======================================================
ArrayList
it is implementation class of List interface.
Hetrogeneous objects are allowed.
Duplicate objects are allowed.
it is growable array or resizable array.
Insertion order is preserved.
Null insertion is possible any number of times.
it implements RandomAccess,Serializable,Cloneable interfaces
All the methods in ArrayList are not synchronized and it is not thread safe.
——————————————————
import java.util.*;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList al=new ArrayList(2);
al.add(10);
al.add(20);
al.add(50);
al.add(10);
al.add(“hello”);
System.out.println(“values are”+al);
System.out.println(“size is”+al.size());
al.remove(3);
System.out.println(“size is”+al.size());
System.out.println(“values are”+al);
System.out.println(“values using iterator”);
Iterator it=al.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println(“using list iterator forward”);
ListIterator lit=al.listIterator();
while(lit.hasNext())
{
System.out.println(lit.next());
}
System.out.println(“using list iterator backward”);
while(lit.hasPrevious())
{
System.out.println(lit.previous());
}
}//main
}//class
===========================================================
Vector
it is a legacy collection class
It is a implemented class for List interface
it is resizable or growable array.
Insertion order is preserved
Duplicates are allowed
null insertion is possible
Vector class implements RandomAccess ,Serializable,Cloneable interfaces
All methods present in Vector class are synchronized hence Vector class object is thread safe.

import java.util.*;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
for(int i=0;i<10;i++)
{
v.addElement(new Integer(i));
}
System.out.println(v);
System.out.println(v.capacity()); // 10
v.add(“a”);
v.add(“b”);
v.add(“c”);
System.out.println(v.capacity()); // 20
System.out.println(v);

System.out.println(“values using iterator”);
Iterator it=v.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println(“using list iterator forward”);
ListIterator lit=v.listIterator();
while(lit.hasNext())
{
System.out.println(lit.next());
}
System.out.println(“using list iterator backward”);
while(lit.hasPrevious())
{
System.out.println(lit.previous());
}
}
}

what is the difference between vector and ArrayList ?
=========================================================
Map
•it is a inteface from java.util which can be used for representing a group of Objects as key,value pairs.
Both keys and values should be objects
Keys can not be duplicated but values can be duplicated.
diagram:
Entry
It is inner interface of Map.
In the Map each key,value pair is considered as Entry object.
interface Map
{
interface Entry
{
Object getKey()
Object getValue()
Object setValue(Object new)
}
}
———————————————–
HashMap
It is the implementation class of Map interface which can be used used to represent a group of objects as key-value pairs.
underlying data structure is Hashtable
Duplicaes keys are not allowed but duplicate values are allowed
Insertion order is not preserved because insertion is based on hashcode of keys.
Heterogeneous objects are allowed for both keys and values
null key is allowed only once
null values are allowed multiple times

import java.util.*;
public class HashMapDemo
{
public static void main(String args[])
{
HashMap<String,Integer> hm=new HashMap<String,Integer>();
hm.put(“orange”,1000);
hm.put(“apple”,2000);
hm.put(“banana”,3000);
hm.put(“grapes”,4000);
System.out.println(hm);//hm.toString()

System.out.println(“for-each loop”);
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+” “+m.getValue());
}

System.out.println(hm.put((“orange”),new Integer(1001)));//1000
System.out.println(hm);//hm.toString()

Set s=hm.keySet();
System.out.println(s);

Collection c=hm.values();
System.out.println(c);

Set s1=hm.entrySet();
System.out.println(s1);

System.out.println(“values using iterator”);
Iterator i1=s1.iterator();
while(i1.hasNext())
{
Map.Entry me=(Map.Entry)i1.next();
System.out.println(me.getKey()+”\t”+me.getValue());
}

}
}
====================================================
LinkedHashMap(1.4 verison)
It is child class of HashMap.
It is similar to HashMap.
In the case of HashMap the insertion order is not preserved but in the case of LinkedHashMap insertion order is preserved.

import java.util.*;
public class LinkedHashMapEX {
public static void main(String… args)
{
LinkedHashMap<String,Integer> lhp=new LinkedHashMap();
lhp.put(“orange”,1000);
lhp.put(“apple”,2000);
lhp.put(“banana”,3000);
lhp.put(“grapes”,4000);
System.out.println(lhp);
}}

=====================================================
IdentityHashMap
In case of HashMap JVM uses the equals() method to identify the duplicate keys
in casse of IdentityHashMap it uses == operator to identify the duplicate keys(references)

import java.util.*;
public class IDentityHashMapEx
{
public static void main(String… args)
{
HashMap hm=new HashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
hm.put(i1,”orange”);
hm.put(i2,”apple”);
System.out.println(hm);

IdentityHashMap im=new IdentityHashMap ();
Integer i3=new Integer(10);
Integer i4=new Integer(10);
im.put(i3,”orange”);
im.put(i4,”apple”);
System.out.println(im);
}
}
————————————————-
WeakHashMap:
it is the implementation class for Map interface.
HashMap dominates the garbage collector ie if any objects are associated with the HashMap even though that object does not have any external references Garbage collector is not allowed to destroy that object

HashMap hm =new HashMap();
hm.put(new Integer(1),new Float(10.5f));
But garbage collector dominates the WeakHashMap that is in case of WeakHashMap if the key is not reachable garbage collector is allowed to destroy whole entry associated with the key.

import java.util.*;
class Temp
{
public void finalize()
{
System.out.println(“finalize() Called”);
}
public String toString()
{
return “temp”;
}
}
public class WeakHashMapEx
{
public static void main(String[] args)
{
WeakHashMap whp=new WeakHashMap();
Temp t=new Temp();
whp.put(t,”orange”);
System.out.println(whp);
t=null;
System.gc();
System.out.println(whp);
}
}
=====================================
SortedMap:
It is child interface of Map
If we want to store the elements based on some sorting order(default ascending) of keys we should go for the SortedMap.
————————————-
NavigableMap
It is introduced in 1.6 version
It is child interface of SortedMap and defines several method for navigation purpose.
———————————————–
TreeMap:
It implements the SortedMap and NavigableMap interfaces.
underlying datastructure is Red-Black Tree
Insertion order is not preserved
Duplicate keys are not allowed but values may be duplicated
Heterogeneous objects are not allowed for the keys but values may be heterogeneous.
first entry null key insertion is possible to the empty treemap but after if you try to add any other entry we will get the NullPointerException
If you are trying to add an entry with the null key to an already exsting TreeMap we will get the NullPointerException
import java.util.TreeMap;

public class TreeMapEx
{
public static void main(String[] args)
{
TreeMap tm=new TreeMap();
//tm.put(null,”apple”); NullPointerException
//tm.put(“hero”,”java”); ClassCastException
tm.put(new Integer(200) ,”apple”);
tm.put(new Integer(100),”orange”);
tm.put(new Integer(300),”grapes”);
System.out.println(“The TreeeMap is”+tm);
}
}
=============================================

=============================================
Hashtable
it is a legacy Map and can be used to store objects as key,value pairs.
underlying data sturucture is Hashtabe
Duplicates keys are not allowed but duplicate values are allowed
null insertion is not possible for both keys and values
all methods are synchronized
insertion order is not preserved because it is based on hashcode of keys
heterogeneous Objects are allowed for both keys and values

import java.util.*;
class HashTableEx
{
public static void main (String args[])
{
Hashtable<String,Integer> ht=new Hashtable<String,Integer>();
//ht.put(null,new Integer(45));
ht.put(“sachin”,57);
ht.put(“dravid”,75);
ht.put(“dhoni”,145);
ht.put(“kaif”,15);
System.out.println(ht);//ht.toString()
Enumeration<String> e=ht.keys();
while(e.hasMoreElements())
{
String key=e.nextElement();
Integer value=ht.get(key);
System.out.println(key+” “+value);
}
}//main
}//class
=====================================================
Properties
It is the child class of Hashtable
For Properties both keys and values must be Strings
it is used to read the data from properties file.
A properites file is text file having the extension of .properties
properties file contains key and value seperated by =
#is the comment in properties file.

Methods:
String getProperty(String key);
void setProperty(String key,String value);
void load(InputStream stream);
void store(OutputStream stream,String comment);

import java.util.*;
import java.io.*;
public class PDemo {
public static void main(String[] args ) throws Exception
{
Properties p=new Properties();
FileInputStream fis=new FileInputStream(“abc.properties”);
p.load(fis);//Load the file
System.out.println(p.getProperty(“orange”));
System.out.println(p.getProperty(“apple”));
p.setProperty(“banana”,”300″);
FileOutputStream fos=new FileOutputStream(“abc.properties”);
p.store(fos,”adding new value”);
}
}

abc.properties
—————
apple=200
orange=100